How to upload images using PHP

They have: 1 posts

Joined: Jul 2009

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>

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";}

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";}

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";}

greg's picture

He has: 1,581 posts

Joined: Nov 2005

That's not only an INSECURE approach, it's badly written, wont work and incomplete!

The mime type alone is not really a secure method to identify a file type.
You can use it, but in conjunction with other things, such as checking file extension(s) (is .jpg or is .gif etc).

Also, why not allow png? It's one of the best compression formats for the web.

You set the variable "$msg" to contain various error messages, but never actually use the var (never echoed).

You perform an "IF" test on these two variables: $userfile_size AND $userfile_type, but you haven't actually set them to be anything, they are null and therefore them checking if filesize and type is as should be will always return FALSE (i.e. they will be allowed regardless of their type and size).

Besides, you didn't set the required file size limit in the html form anyway.

________________

All in all, it's a fairly bad tutorial considering you are a web development site! Do you provide clients with this poor level of security in their code and sites?
Also, this is worded "EXACTLY" on other sites, so is this your tutorial or someone else's you have copied?

I can only advise anyone reading this to stay WELL CLEAR of using elevationnewmedia.com's web services!

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.