SitePoint Sponsor

User Tag List

Results 1 to 21 of 21
  1. #1
    SitePoint Enthusiast
    Join Date
    Jan 2010
    Posts
    54
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    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

    Code:
    <?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>';
     ?>

  2. #2
    SitePoint Wizard
    Join Date
    Nov 2005
    Posts
    1,191
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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

  3. #3
    SitePoint Enthusiast
    Join Date
    Jan 2010
    Posts
    54
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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?

    Code:
    <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>

  4. #4
    Non-Member
    Join Date
    Oct 2009
    Posts
    1,852
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Lost curly bracket most likely

  5. #5
    SitePoint Wizard
    Join Date
    Nov 2005
    Posts
    1,191
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    PHP Code:
    <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:
    Code PHP:
    <?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.

  6. #6
    SitePoint Enthusiast
    Join Date
    Jan 2010
    Posts
    54
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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

    Code:
    $target_path = $target_path . basename($_FILES['uploadedfile']['name']); 
    
    	if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {

  7. #7
    rajug.replace('Raju Gautam'); bronze trophy Raju Gautam's Avatar
    Join Date
    Oct 2006
    Location
    Kathmandu, Nepal
    Posts
    4,013
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    This is not the proper way to check whether the file is uploaded or not:
    PHP Code:
    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:
    PHP Code:
    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?
    Mistakes are proof that you are trying.....
    ------------------------------------------------------------------------
    PSD to HTML - SlicingArt.com | Personal Blog | ZCE - PHP 5

  8. #8
    SitePoint Enthusiast
    Join Date
    Jan 2010
    Posts
    54
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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"
    Code:
    "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>
    Code:
    <!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>
    
     <?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->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);
    
    // @@@@@@
    // 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 '<p>Click <a href="member-index.php">here</a> to go back</p>';
     ?>
    
    </body>
    </html>

  9. #9
    SitePoint Enthusiast
    Join Date
    Jan 2010
    Posts
    54
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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\tmp\php5307.tmp' to ('http://localhost/Blean_Photos/images/invalid carriage.jpg') in ('C:\wamp\www\Blean_Photos\add_file.php') on line 25

  10. #10
    dooby dooby doo silver trophybronze trophy
    spikeZ's Avatar
    Join Date
    Aug 2004
    Location
    Manchester UK
    Posts
    13,788
    Mentioned
    153 Post(s)
    Tagged
    3 Thread(s)
    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
    PHP Code:
     $target_path "Blean_Photos/images/"
    Mike Swiffin - Community Team Advisor
    Only a woman can read between the lines of a one word answer.....

  11. #11
    SitePoint Enthusiast
    Join Date
    Jan 2010
    Posts
    54
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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\tmp\php247F.tmp' to 'Blean_Photos/images/invalid carriage.jpg' in C:\wamp\www\Blean_Photos\add_file.php on line 25

    thanks!

  12. #12
    SitePoint Enthusiast
    Join Date
    Jan 2010
    Posts
    54
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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

  13. #13
    rajug.replace('Raju Gautam'); bronze trophy Raju Gautam's Avatar
    Join Date
    Oct 2006
    Location
    Kathmandu, Nepal
    Posts
    4,013
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by saunders1989 View Post
    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:
    PHP Code:
    $target_path 'images/'
    Mistakes are proof that you are trying.....
    ------------------------------------------------------------------------
    PSD to HTML - SlicingArt.com | Personal Blog | ZCE - PHP 5

  14. #14
    SitePoint Enthusiast
    Join Date
    Jan 2010
    Posts
    54
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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

  15. #15
    dooby dooby doo silver trophybronze trophy
    spikeZ's Avatar
    Join Date
    Aug 2004
    Location
    Manchester UK
    Posts
    13,788
    Mentioned
    153 Post(s)
    Tagged
    3 Thread(s)
    thats because you aren;t actually running the query, just constructing it.

    You need mysql_query($query); to run the query
    PHP Code:
    $query "INSERT INTO `images` (`name`, `mime`, `size`, `data`, `created`, `image_path`)
                 VALUES ('
    {$name}', '{$mime}', {$size}, '', NOW(), '{$image_path}')";
    $result mysql_query($query); 
    Mike Swiffin - Community Team Advisor
    Only a woman can read between the lines of a one word answer.....

  16. #16
    SitePoint Enthusiast
    Join Date
    Jan 2010
    Posts
    54
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    ahhh okay. i added this bit of code
    PHP Code:
    $dbLink->query($query); 
    but now it dont want to upload to the folder anymore

  17. #17
    SitePoint Enthusiast
    Join Date
    Jan 2010
    Posts
    54
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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

  18. #18
    rajug.replace('Raju Gautam'); bronze trophy Raju Gautam's Avatar
    Join Date
    Oct 2006
    Location
    Kathmandu, Nepal
    Posts
    4,013
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    See in your php.ini what is max_upload_size. If it is less than 2mb then increase it and try.
    Mistakes are proof that you are trying.....
    ------------------------------------------------------------------------
    PSD to HTML - SlicingArt.com | Personal Blog | ZCE - PHP 5

  19. #19
    SitePoint Enthusiast
    Join Date
    Jan 2010
    Posts
    54
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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

  20. #20
    Non-Member
    Join Date
    Oct 2009
    Posts
    1,852
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    did you check actual value after this?

  21. #21
    SitePoint Enthusiast
    Join Date
    Jan 2010
    Posts
    54
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    yer i checked it. and i apologise for my stupidity i exited out of wamp and restarted it and it works now. i apologise for being so bone idely thick

    THANK YOU FOR YOUR HELP!!!


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •