Upload path to database

Hi, i am struggling to get this part before i tackle the next part. i have a upload form i have created (very simple just a browse and a upload button) when you click upload this code is run (shown below) but that stores the file in the database as a file using blob but what i would really like to do is upload the images to a this folder (‘http://localhost/Blean_Photos/images’) and have the path stored in the database. i havent a clue on how to change my code i have now to do that. the next part would be to display the images but i would like to tackle one part at a time

thank you to anyone who could help

<?php
 // Check if a file has been uploaded
 if(isset($_FILES['uploaded_file'])) {
     // Make sure the file was sent without errors
     if($_FILES['uploaded_file']['error'] == 0) {
         // Connect to the database
         $dbLink = new mysqli('localhost', 'root', '', 'gallery');
         if(mysqli_connect_errno()) {
             die("MySQL connection failed: ". mysqli_connect_error());
         }
  
         // Gather all required data
         $name = $dbLink->real_escape_string($_FILES['uploaded_file']['name']);
         $mime = $dbLink->real_escape_string($_FILES['uploaded_file']['type']);
         $data = $dbLink->real_escape_string(file_get_contents($_FILES  ['uploaded_file']['tmp_name']));
         $size = intval($_FILES['uploaded_file']['size']);
  
         // Create the SQL query
         $query = "
             INSERT INTO `images` (
                 `name`, `mime`, `size`, `data`, `created`
             )
             VALUES (
                 '{$name}', '{$mime}', {$size}, '{$data}', NOW()
             )";
  
         // Execute the query
         $result = $dbLink->query($query);
  
         // Check if it was successfull
         if($result) {
             echo 'Success! Your file was successfully added!';
         }
         else {
             echo 'Error! Failed to insert the file'
                . "<pre>{$dbLink->error}</pre>";
         }
     }
     else {
         echo 'An error accured while the file was being uploaded. '
            . 'Error code: '. intval($_FILES['uploaded_file']['error']);
     }
  
     // Close the mysql connection
     $dbLink->close();
 }
 else {
     echo 'Error! A file was not sent!';
 }
  
 // Echo a link back to the main page
 echo '<p>Click <a href="member-index.php">here</a> to go back</p>';
 ?>

create a path variable, eg /path/to/images/
concatenate $_FILES[‘file’][‘name’] to the end
use move_uploaded_file() to move the uploaded file from the tmp directory to your path above
store the path in the database

okay i think ive done it but i get a error on the html tag at the bottom of the page can you see any reason why that would bring me a parse error on the html tag?

<html>
<head>
</head>
<body>
// Check if a file has been uploaded
if(isset($_FILES['uploaded_file'])) {
     // Make sure the file was sent without errors
     if($_FILES['uploaded_file']['error'] == 0) {
		 

		 $target_path = "http://localhost/Blean_Photos/images/";

$target_path = $target_path . basename( $_FILES['uploadedfile']['name']); 

if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
    echo "The file ".  basename( $_FILES['uploadedfile']['name']). 
    " has been uploaded";
	
	$dbLink = new mysqli('localhost', 'root', '', 'gallery');
         if(mysqli_connect_errno()) {
             die("MySQL connection failed: ". mysqli_connect_error());
         }  // You missed this closing curly brace here
			 
         // Gather all required data
         $name = $dbLink->real_escape_string($_FILES['uploaded_file']['name']);
         $mime = $dbLink->real_escape_string($_FILES['uploaded_file']['type']);
         $size = intval($_FILES['uploaded_file']['size']);
         $image_path = $dbLink->real_escape_string($target_path);

	$query = "INSERT INTO `images` (`name`, `mime`, `size`, `data`, `created`, `image_path`)
             VALUES ('{$name}', '{$mime}', {$size}, '', NOW(), '{$image_path}')";
			 

		 
	 }
		 
 else {
     echo 'Error! A file was not sent!';
 }
 
	 }
  
 // Echo a link back to the main page
 echo '<p>Click <a href="member-index.php">here</a> to go back</p>';
 ?>
</body>
</html>

Lost curly bracket most likely


<body>
// Check if a file has been uploaded
if(isset($_FILES['uploaded_file'])) {

There is no <?php start tag.

Also, you should do this outside the html. Whether at the top of the page:


<?php
// bunch of logic etc here
$var = 'something';
...
// now start html using vars
?>

<html>
<head>
</head>
<body>
<?php echo $var'; ?>

or using templates, either way, just try to keep the logic out of the presentation.

yer it was a lost curly bracket thanks for that i found it. im now getting a really odd error.

im getting a undefinded index on both lines which is related to ‘uploadedfile’ (code below). do you know what reason that would bring up this error? as i can see the ‘uploadedfile’ looks as if it should work


$target_path = $target_path . basename($_FILES['uploadedfile']['name']); 

	if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {

This is not the proper way to check whether the file is uploaded or not:


if(isset($_FILES['uploaded_file'])) {

Because the $_FILES array will be set with error so it will always be true even if you don’t upload a file. So try once print_r($_FILES) for sure.

So I would prefer:


if(is_uploaded_file($_FILES['uploaded_file']['tmp_name'])) {

And for the notice (undefined index ‘uploadedfile’), maybe the spelling is wrong. Just a wild guess. Can we see your form/html for sure?

i found what was wrong it was a couple of mistakes i have uploaded_file not uploadedfile. my bad i skim over things too quick. but now i get this error

Warning: move_uploaded_file(‘http://localhost/Blean_Photos/images/invalid carriage.jpg’) [function.move-uploaded-file]: failed to open stream: HTTP wrapper does not support writeable connections in C:\wamp\www\Blean_Photos\add_file.php on line 25

Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move ‘C:\wamp\ mp\php5307.tmp’ to (‘http://localhost/Blean_Photos/images/invalid carriage.jpg’) in (‘C:\wamp\www\Blean_Photos\add_file.php’) on line 25

sure my upload form looks like this (first code) and the second code is my add_file.php file (Second code) if i was to change to your code the if(is_uploaded_file($_FILES[‘uploaded_file’][‘tmp_name’])) {. would i have to change much more of my code to implement that in?

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>

 <form action="add_file.php" method="post" enctype="multipart/form-data">
         <input type="file" name="uploaded_file"><br>
         <input type="submit" value="Upload file">
     </form>

</body>
</html>
&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;head&gt;
&lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt;
&lt;title&gt;Untitled Document&lt;/title&gt;
&lt;/head&gt;

&lt;body&gt;

 &lt;?php
 // Check if a file has been uploaded
if(isset($_FILES['uploaded_file'])) {
     // Make sure the file was sent without errors
     if($_FILES['uploaded_file']['error'] == 0) {
		 

// @@@@@@@@@@@@@@
// Path is wrong. You have to specify the path of the folder on the web server
// Typically, it'd be something akin to "var/www/Blean_Photos/images"
// Also make sure the folder exists and that you have write permissions for it
		 $target_path = "http://localhost/Blean_Photos/images/";

		$target_path = $target_path . basename( $_FILES['uploadedfile']['name']); 

	if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
	// @@@@@@@@@@@@@@
	// this echo is not really necessary
    echo "The file ".  basename( $_FILES['uploadedfile']['name']). 
    " has been uploaded";
	
	$dbLink = new mysqli('localhost', 'root', '', 'gallery');
         if(mysqli_connect_errno()) {
             die("MySQL connection failed: ". mysqli_connect_error());
         }  // You missed this closing curly brace here
			 

// @@@@@@@@@@@@@
// To keep things simple, we'll keep your DB structure the same except for 1 thing:
// add a field of type 'varchar' with 100 or so characters, in your 'images' table.
// Name it something like "image_path".
// I copied over your "old" code but note that I got rid of "data" (which was your image)
// and added $image_path variable instead

         // Gather all required data
         $name = $dbLink-&gt;real_escape_string($_FILES['uploaded_file']['name']);
         $mime = $dbLink-&gt;real_escape_string($_FILES['uploaded_file']['type']);
         $size = intval($_FILES['uploaded_file']['size']);
         $image_path = $dbLink-&gt;real_escape_string($target_path);

// @@@@@@
// Note changes to your query as well
// Make sure you added the "image_path" field to the "images" table!!
	$query = "INSERT INTO `images` (`name`, `mime`, `size`, `data`, `created`, `image_path`)
             VALUES ('{$name}', '{$mime}', {$size}, '', NOW(), '{$image_path}')";	 
	 }
		 
 else {
     echo 'Error! A file was not sent!';
 }
 
	 }
	 
}
  
 // Echo a link back to the main page
 echo '&lt;p&gt;Click &lt;a href="member-index.php"&gt;here&lt;/a&gt; to go back&lt;/p&gt;';
 ?&gt;

&lt;/body&gt;
&lt;/html&gt;

and now you have found the next sticking up twig to trip you up!
PHP wont allow full URL’s in the upload path.
You would need to use


 $target_path = "Blean_Photos/images/";

thanks for that. ive changed it to that and i can see it wants to go in the right folder but i think im getting this errors (below) because i dont seem to have right access to phpmyadmin. does anyone know how to allow that.

Warning: move_uploaded_file(Blean_Photos/images/invalid carriage.jpg) [function.move-uploaded-file]: failed to open stream: No such file or directory in C:\wamp\www\Blean_Photos\add_file.php on line 25

Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move ‘C:\wamp\ mp\php247F.tmp’ to ‘Blean_Photos/images/invalid carriage.jpg’ in C:\wamp\www\Blean_Photos\add_file.php on line 25

thanks!

i think that error is something to do with not being allowed to write to the database. im not sure how to have write access on phpmyadmin. ive gone to the folders where i would be uploading it to and right clicked and made sure the read only button was unticked. but apart from that i dont know where to go

There is nothing to do with phpmyadmin here. Phpmyadmin is the only tool or web application that helps you to manage mysql databases. As far as i know the problem is all about the folder does exists or not. There should not be any permission problems since you seem to be working in windows system. Are you sure you have already created a folder ‘images’ inside ‘C:\wamp\www\Blean_Photos’ path? If not create it once and try. And since you are in the same folder ‘C:\wamp\www\Blean_Photos’ so i think no need to give full path like just do like this:


$target_path = 'images/';

i changed the target path to what you said and i am able to upload the image to the folder which is good. thank you for that.

the only problem i find is when i check my database the file doesnt get updated there and so i dont know why it isnt writing to the database

thanks

thats because you aren;t actually running the query, just constructing it.

You need mysql_query($query); to run the query


$query = "INSERT INTO `images` (`name`, `mime`, `size`, `data`, `created`, `image_path`)
             VALUES ('{$name}', '{$mime}', {$size}, '', NOW(), '{$image_path}')";
$result = mysql_query($query);

ahhh okay. i added this bit of code

$dbLink->query($query);

but now it dont want to upload to the folder anymore

update:

it uploads to the database and will upload to the folder i need it to. BUT for some reason it doesnt like me uploading any largeish files above 2mb i havent got a max size set on my form page so i dont know why it doesnt let me as im only storing the image path in the database.

any ideas?

Thanks

See in your php.ini what is max_upload_size. If it is less than 2mb then increase it and try.

i have two php.ini files and ive changed both of them to this:

; Maximum allowed size for uploaded files.
; http://php.net/upload-max-filesize
upload_max_filesize = 5M

still doesnt allow me to upload a 4.41mb file

did you check actual value after this?