Upload code

Discussion in 'PHP' started by davenet, Jul 18, 2007.

  1. #1
    How to upload image file in PHP?

    input_data_mhs.php
    
    echo "
    		<h1 align=\"center\">Input Data Mahasiswa</h1>
    		<form method=\"post\" action=\"input_data1.php\" ENCTYPE=\"MULTIPART/FORM-DATA\">;"
    
    echo "
    	<tr>
    		<td>Foto</td>
    		<td><input type=\"FILE\" accept=image/jpeg name=\"foto\"></td></tr>";	
    
    echo "
    	<tr>
    	<td><input type=\"submit\" value=\"submit\"></td>
    	<td><input type=\"reset\" value=\"reset\"></td>
    	</tr>
    		
    </table>
    ";
    
    PHP:

    input_data1.php
    
    
    ...
    if (!$_FILES['foto'])   
    echo "Required parameter foto is missing.<br />";
    else $foto = $_FILES['foto'];
    
    
    mysql_query ("INSERT INTO mhs (nim, nama, jk, jurusan, foto) VALUES ('$nim', '$nama', '$jk', '$jurusan', '$foto')", $koneksi) or die (mysql_error());
    
    PHP:
    Above are some of the codes that I wrote. I wonder why when I check the database in phpMyAdmin the Image file that I have uploaded are stored as Array. I cannot check the real file name nor post the image that I have uploaded on the web.
     
    davenet, Jul 18, 2007 IP
  2. exodus

    exodus Well-Known Member

    Messages:
    1,900
    Likes Received:
    35
    Best Answers:
    0
    Trophy Points:
    165
    #2
    The reason it is stored as an Array() is because $_FILES is an array like $_POST and $_GET would be. There are other varibles you have to extracted from the $_FILES variable.

    
    <?php
    function show_array($arr)
    {
       echo "<pre>";
       print_r($arr);
       echo "</pre>";
    }
    
    if (empty($_FILES['foto']['tmp_name']))   
    { 
      echo "Required parameter foto is missing.<br />";
    }
    else 
    {
      $foto = $_FILES['foto']['name'];
      echo show_array($_FILES);
    }
    ?>
    
    PHP:
    http://www.tizag.com/phpT/fileupload.php

    You should read over a few more tutorials. You almost have it. Don't forget to rename the temp file into the files name and copy it over to a directory. Which can be done with the single copy() php command. Then store the sql data.

    .
     
    exodus, Jul 18, 2007 IP
  3. davenet

    davenet Peon

    Messages:
    46
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    
    
    function show_array($arr){   
    echo "<pre>";   
    print_r($arr);   
    echo "</pre>";
    }
    if (!$_FILES['foto']['tmp_name'])   
    echo "Required parameter foto is missing.<br />";
    else 
    {
    $foto = $_FILES['foto']['name'];
    echo show_array($_FILES);
    }
    
    mysql_query ("INSERT INTO mhs (nim, nama, jk, jurusan, foto) VALUES ('$nim', '$nama', '$jk', '$jurusan', '$foto')", $koneksi) or die (mysql_error());
    
    
    PHP:
    I made some revision.

    Does the above code good enough to have the file stored? why do I need to copy it to a directory? so that I can post the image file later on?

    Does the sql_query also store the same image file in mySQL?

    Also what's the code to posted on the web? just so that I can see that it really being stored on the database and can be posted.

    Thanks
     
    davenet, Jul 18, 2007 IP
  4. DavidAusman

    DavidAusman Well-Known Member

    Messages:
    399
    Likes Received:
    6
    Best Answers:
    0
    Trophy Points:
    108
    #4
    
    //First you will need to define what files are allowed
    $imgExt = array("image/png","image/jpeg","image/jpg","image/gif");
    
    //Max image size. Define max image limit before allowing others to upload
    $maxSize = 1048000;
    
    //Image upload details
    $tmp = $_FILES['filename']['tmp_name'];
    $size = $_FILES['filename']['size'];
    $type= $_FILES['filename']['type'];
    $name= $_FILES['filename']['name'];
    
    //If it is not what you supported, del from tmp folder and don't upload!
    if(!in_array($type, $imgExt) || $size > $maxSize) {
    unlink($tmp);
    }
    else {
    copy($tmp, "new location here");
    unlink($tmp);
    }
    
    //Additionally, if you need to insert into DB
    mysql_query("INSERT INTO whatever(`fotoname`) VALUES('$name')");
    
    PHP:
     
    DavidAusman, Jul 18, 2007 IP
  5. davenet

    davenet Peon

    Messages:
    46
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Ha ha, thanks. now I can view the file name in mysql database:

    0100910060 Vince 1 0 Acc EMT brosure.jpg

    Except that I cannot view the file being copied to my image folder. I check my File Manager and the specific folder that I suppose to have the file copied to is still empty.

    input_data1.php
    
    
    // print file specification
    function show_array($arr){   
    echo "<pre>";   
    print_r($arr);   
    echo "</pre>";
    }
    
    //First you will need to define what files are allowed
    $imgExt = array("image/png","image/jpeg","image/jpg","image/gif");
    //Max image size. Define max image limit before allowing others to upload
    $maxSize = 1048000;
    
    //Image upload details
    $fototmp = $_FILES['filename']['tmp_name'];
    $fotosize = $_FILES['filename']['size'];
    $fototype= $_FILES['filename']['type'];
    $fotoname= $_FILES['filename']['name'];
    
    //If it is not what you supported, del from tmp folder and don't upload!
    if(!in_array($fototype, $imgExt) || $fotosize > $maxSize) {
    // delete command
    unlink($fototmp);
    }else {
    copy($fototmp, "image/");
    unlink($fototmp);
    }
    
    
    mysql_query ("INSERT INTO mhs (nim, nama, jk, jurusan, foto) VALUES ('$nim', '$nama', '$jk', '$jurusan', '$fotoname')", $koneksi) or die (mysql_error());
    
    
    PHP:
    Any suggestion ?
     
    davenet, Jul 18, 2007 IP
  6. exodus

    exodus Well-Known Member

    Messages:
    1,900
    Likes Received:
    35
    Best Answers:
    0
    Trophy Points:
    165
    #6
    Don't forget to CHMOD the folder you want to copy the images into to 777. It has to be writeable. Also, sounds dumb, but don't forget to create the folder /image too. :)

    You can get rid of the function show_array($arr) portion. I put that to show you that file variable has more varibles for you to get out of it.
     
    exodus, Jul 19, 2007 IP
  7. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #7
    Change:
    
    copy($fototmp, "image/");
    
    PHP:
    To:
    
    move_uploaded_file($fototmp, "image/{$fotoname}");
    
    PHP:
    But all in all, your code is not very secure. And there's no need to unlink() the temp files since they're deleted automatically at the end of the request.
     
    nico_swd, Jul 19, 2007 IP
  8. davenet

    davenet Peon

    Messages:
    46
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #8
    These error appears:

    server/tmp/phpQTfxpJ44570image/pjpeg100_5.JPG
    Warning: move_uploaded_file(/tmp/phpQTfxpJ) [function.move-uploaded-file]: failed to open stream: No such file or directory in /home/davenet/public_html/php/input_data1.php on line 67

    Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/tmp/phpQTfxpJ' to 'image/100_5.JPG' in /home/davenet/public_html/php/input_data1.php on line 67

    Line 67 is:
    move_uploaded_file($fototmp, "image/{$fotoname}");

    I have image/ and have also tried to create tmp/ directory and no difference.

    note: CHMOD image is 777
     
    davenet, Jul 19, 2007 IP
  9. DavidAusman

    DavidAusman Well-Known Member

    Messages:
    399
    Likes Received:
    6
    Best Answers:
    0
    Trophy Points:
    108
    #9
    CHMOD 0777 is vulnerable to attack. People can easily upload scripts to your folder and execute it, because you set

    World => read write and execute
    Group => read write and execute
    User => read write and execute

    The much much saver way for an image file is 0755.

    World => read and execute
    Group => read and execute
    User => read write and execute // Only you as the owner do everything!

    Secondly, it is a good programming habit for you to unlink any images from temporary folder even if it is automatically deleted. Just as register globals, using $_POST['name'] is much much saver than $name itself ;)
     
    DavidAusman, Jul 19, 2007 IP
  10. DavidAusman

    DavidAusman Well-Known Member

    Messages:
    399
    Likes Received:
    6
    Best Answers:
    0
    Trophy Points:
    108
    #10

    move_uploaded_file is a function that make sure the files is uploaded via HTTP protocol, it does not check what type of files you are uploading. It could be scripts, images or whatever. If I recall correctly, as long as it is via HTTP(s) protocol, it is a valid form.

    The most secure way to upload files is to check everything, make sure it is valid :)
     
    DavidAusman, Jul 19, 2007 IP
  11. DavidAusman

    DavidAusman Well-Known Member

    Messages:
    399
    Likes Received:
    6
    Best Answers:
    0
    Trophy Points:
    108
    #11
    Make sure you have the correct path to the destination folder. For example: your script is located here => http://davenet.com/uploading/script.php and your destination folder is => http://davenet.com/image

    To do this, you will need copy($tmp, "../image");
    The (..) means move up one level and enter to image folder.

    And also, you must have to provide name to your image. In most cases, when I create uploading form, I use timestamp as my imagename, so it will be copy($tmp, "../image/".time().".gif"); or if you want to use your image name, then it will be copy($tmp, "../image/".$_FILES['filename'][name]);
     
    DavidAusman, Jul 19, 2007 IP
  12. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #12
    Since we want to move a file that has been uploaded via HTTP protocol, move_uploaded_file() is slightly safer in this case. Note that I also added the image name to the target path, which was missing in his code.

    And for the record, while talking about security, the type value in $_FILES array is defined by the browser and therefore can't be trusted. More secure is an extension check, so that no one can upload (for example) PHP scripts and run them on your server.

    And you may as well want to have a look at mime_content_type().

    And yet on another note, IE may upload some JPEG images as image/pjpeg.
     
    nico_swd, Jul 19, 2007 IP
  13. davenet

    davenet Peon

    Messages:
    46
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #13
    I successfully upload the image file, store in File Manager and sql Database.

    Just one more problem. How to post them on the web?

    This is the code to post the image:

    input_nilai_mhs.php
    
    
    echo "<img src=\"../image/$row_mhs[5]\" alt=\"$row_mhs[1]\" align=\"center\">";
    
    
    PHP:

    The image location is in:

    Directory/image/100_5.JPG

    Directory/input_nilai_mhs.php

    $row_mhs[5] represents 100_5.JPG
    $row_mhs[1] represents the image name

    The output so far is a box with an X mark in the middle and the image name besides it. What could possibly the problem?
     
    davenet, Jul 20, 2007 IP
  14. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #14
    As this script and the image directory are in the same folder, remove the 2 dots and the slash here: ../image
     
    nico_swd, Jul 20, 2007 IP