php upload script

by krike in PHP & MYSQL / Tutorials on 19 Aug 2009


One day will come that you or one of your clients requires an upload form. If it’s for uploading images or other files…

But how do you start, what is important, how can you secure it. In this tutorial I will guide you through the steps of creating a simple upload form in php and how to add some basic security.

example_form

The first step is offcourse create an upload form, copy/paste the code below into a php file. Name it upload.php also create a directory images and chmod it to 0777

<form id="upload" action="<?php echo $_SERVER['PHP_SELF']; ?>" name="upload" enctype="multipart/form-data" action="" method="post">
<label for="file">Upload image: </label><input id="file" type="file" name="file" /><br />
<input type="submit" name="submit" value="upload" />
</form>

So let’s have a look at the form

– First we open the form give it a name, id, post method, action* and most important of all we added the enctype=”multipart/form-data” this is extremely important to add when you want to upload files, if you do not add this you won’t be able to upload anything but you won’t have any errors either. So a bit tricky to debug, a good thing to do is always check if you included the enctype

– Second we creat an input file of type file with a name of file. Again the name is important because we will use that to catch the upload file so do not forget to add it.

– And last but not least the input with type submit (submit button) here also the name (name=”submit”) is important !

Remember that the action normally links to a file that will process the entered data in the form. We added <?php echo $_SERVER[‘PHP_SELF’]; ?> in the action rather then linking to another php file because this code will tell your server to send the entered data to the exact same file. If your file is called upload.php it will use that file to process the entered data.

upload_formulier_start

Above the doctype add following code

&lt;?php
if(isset($_POST['submit']))
{

}
?&gt;

This code will check if the post with name submit exist (that’s what the isset function does), so with other words if a user submitted the form. Because we only want to execute some code, upload the image for example, when the user submitted the form.

if_isset_submit

When we want to catch the submitted data (and if you specified the post method in the form) you must use the $_POST variable like we did to check if the form was submitted ($_POST[‘submit]). However when it comes to uploading files you need to use the global variable $_FILES.

Add this code in the if-lus you just created

//1 Name of the file
$filename = $_FILES['file']['name'];
//2 Temporary directory of the file
$filetmp = $_FILES['file']['tmp_name'];
//3 File size
$filesize = $_FILES['file']['size'];
//4 File type
$filetype = $_FILES['file']['type'];
//5 Create the path to the image
$path = &quot;images/&quot;.$filename;

Thanks to the $_FILES variable you can catch different aspects of a file. Make sure that in the first part of the array you added the name of the input file used to upload (here we called it ‘files’)

We will then catch in the second part of the array

the name: this is just the name of the file and is obviously important to catch when uploading.

the temporary directory: This is the temporary directory where we uploaded the file, later we will use it to move the file to the images directory

the file size: It’s always a good thing to know how big the file size is when you don’t want your users to upload big files

the file type: This is the file type to see if it’s an image, a document or other.. that the user uploade. If you think about restricting your upload form to specific file types

Finally we will attach the directory with the filename to create the path where the image will be uploaded.

files_variable_and_path

to see if everything has been setup correctly you can always use print_r(); to print the array. Add the folowing code under the $path variable (but still in the if-lus)

printr

Now it’s time to move the file from the temporary directory to the images directory, we will use the move_uploaded_file() function for this. Add the following code to your php file

if(move_uploaded_file($filetmp, $path))
{
echo&quot;Image succesfully uploaded&quot;;
}
else
{
echo&quot;Image could not be uploaded&quot;;
}

We need to pass in 2 parameters, the first one is the temporary directory which we saved in the variable $filetmp and the second is the $path where we attache images/ with the filename. A good thing to do is add it in an if-lus to see if the function executed correctly, if not show message Image could not be uploaded otherwise if it executed correctly show Image succesfully uploaded

move_upload_file

So that’s all you require to upload a file or image, however I do not recommend to upload this to a real server unless it’s only for testing purposes. Not checking what the user upload is a big security risk you better not take !! So we’ll add some basic security

Some people use functions to check for the extention of a file, this is a big mistake !! you can easily change a javascript file extention (.js) to an image file (.gif) and the script will validate the file and upload, the user can then access the uploaded file and execute some code on your website. So not recommended !! You should check for the file type, also know as mime type, rather then the extention.

If you look back in this tutorial we printed out the array with the print_r() function, you will notice that one of the options is the file type – [type] => image/jpeg, this is the value we stored in the $filetype variable and it’s that variable we are going to use to check what file the user uploaded.

Behind $path add

$maxsize= 2000000;

this is the maximum size in bites, you can go to matisse to convert from bites to kb/MB,…

around the move_upload_file() function add the following if-lus

if((($filetype == &quot;image/gif&quot;) || ($filetype == &quot;image/jpeg&quot;) || ($filetype == &quot;image/pjpeg&quot;) || ($filetype == &quot;image/png&quot;)) &amp;&amp; ($filesize &lt; $maxsize))
{

}
else
{
echo &quot;Only gif, jpg, png are allowed extentions. And the maximum size is &quot;.$maxsize.&quot; bites&quot;;
}

we will check if the filetype is a gif, jpeg (pjpeg is for IE only) or a png, and we will also check if the filesize was not exceeded. you can check for other mime types here or just google for it

check_file_types

Tips

1. Do not forget to add the enctype in the form opening tag, it will save you a lot of time when debugging.

2. PHP code which needs to execute put not print anything on the screen should always be added above the doctype.

3. For the purpose of this tutorial I echo’d all the message, but normally it is not a good thing to do. Never print something out above the doctype, save it in a variable ($feedback for example) and then print out the variable in the body of your document (between body tags).

Conclusions

I hope you learned how to create a simple upload form, and to pay attention for certain details (like adding enctype and names to the input fields). I also hope you saw the importance of checking the file type rather then the extention of the file.

If you would like to go deeper in the security of your form I suggest your read the excellent php file upload e-book from scanit

Written by krike

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam sit amet nisl nisl. Ut interdum libero vitae quam ultricies et lacinia elit aliquet. Praesent tincidunt, sem tempus feugiat feugiat, turpis tellus scelerisque erat, sit amet feugiat neque arcu ac lectus. Sed at mi et elit interdum scelerisque vitae eu felis.

krike has written 77 posts.

  • nike

    Generally I do not post on blogs, but I would like to say that this post really forced me to do so! I found your blog on google and read a few of your other posts. I just added you to my Google News Reader. Keep up the good work. Look forward to reading more from you in the future.

  • Pingback: Twitted by programmateur()

  • jana

    nice explanation..its very helpful

    • @jana: thanks 🙂

  • Pingback: | Beyond Venture Design()

  • Pingback: Create a php upload script with basic security | Beyond Venture Design()

  • rob

    thanks for the post 🙂

  • Very clearly explained, easy for non-programmers also.

    • @adrian – thank you, don’t forget to tweet it 🙂

  • Olayinka

    Pls I need the Source file in a zip folder

  • reyampo

    any one can give me the simple program for the image uploading plssssssssssss……………..
    as am steping first level for the php image programs……

    • @rejampo: are you looking for an easy and ready to use solution? I think I know one but I’ll need to search for it. I’ll come back and post it later.