How to upload images using PHP

Discussion in 'PHP' started by SaifKhan, Aug 7, 2009.

  1. #1
    Uploading a file is a basic requirement of most of the websites. In this post, I will explain in detail about how to upload an image using PHP.

    First of all, we will add HTML code to display the browse button to upload an image:


    <FORM ENCTYPE="multipart/form-data"  ACTION="_URL_" METHOD=POST>
    Upload this file: <INPUT NAME="userfile" TYPE="file">
    <INPUT TYPE="submit" VALUE="Send File"></FORM>
    HTML:



    This code will display a text area with a browse button to upload an image.
    Then I'll add PHP code for processing of file upload:

    if ($userfile_size >250000){$msg=$msg."Your  uploaded file size is more than 250KB so please reduce the file size and then  upload. Visit the help page to know how to reduce the file size.<BR>";
    $file_upload="false";}
    PHP:




    Now, we will check that only jpeg or gif files can be uploaded into our server:


    if (!($userfile_type =="image/pjpeg"  OR $userfile_type=="image/gif")){$msg=$msg."Your uploaded file must be of JPG or  GIF. Other file types are not allowed<BR>";
    $file_upload="false";}
    PHP:




    Finally, running this script will add the file to the mentioned directory:


    if(move_uploaded_file ($userfile,  $add)){
    // do your coding here to give a thanks message or any other thing. 
    }else{echo "Failed to upload file Contact Site admin to fix the problem";}
    PHP:
     
    Last edited: Aug 7, 2009
    SaifKhan, Aug 7, 2009 IP
  2. premiumscripts

    premiumscripts Peon

    Messages:
    1,062
    Likes Received:
    48
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Looks like half of the processing code isn't there. Also, some vulnerabilities remain. It's best if anyone wants to implement something like this to simply do a google search instead of relying on tutorials on DP :)
     
    premiumscripts, Aug 7, 2009 IP
  3. oop

    oop Peon

    Messages:
    35
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #3
    yep the main things you should take into check when creating an upload script is as follows

    Filesize (Min / Max)
    File Extensions ( Allowed )
    File Type (simerler to above but the above can be faked so your should always check if its like 'image/png');
    FileName
    File already exists?
    Upload Error checking
    md5 checking (so you would create ahash of the file and then prepend the file like $hash_Myfile.png)

    theres many more but cant be arsed to go threw them but you get the idea
     
    oop, Aug 7, 2009 IP