PHP File Uploads

So you want to upload an image using PHP and an HTML form? Here’s how.

For this I’m going to assume you already know the basics of html forms and some basic php. I’m also only going to upload a file – you could make this part of a larger form and upload a title and description at the same time, but you already know how to do that, right?

This process will be use two files – an html page which will contain the form (which we’ll call form.html) and a php page (which we’ll call upload.php). You could do it all on one page and make it send the data to itself but I’ll let you figure that’d just confuse matters.

The HTML page.

Here’s the code:

<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="2500" /> <!-- !!The above line is unnecesary - see below!! -->
<input type="file" name="myfile" />
<input type="submit" value="GO!" />

OK, let’s take that line by line.

<form action="upload.php" method="post" enctype="multipart/form-data">

This defines the properties of our form. The “action” parameter defines where the data from this form is sent. In this case we’re sending it to upload.php – the page with our php code on it which we’ll get to in a minute.

Method can either be “get” or “post”. “Get” encodes all the values from a form into a URL and then directs the users browser to that URL (e.g. “mypage.php?formdata=goeshere”). This is generally used for getting data from a page (e.g. “news.php?news_article_id=77” might show only news article number 77) whereas “post” is generally used for sending information (the clue’s in the names). As we’re uploading a file we’ll have to use “post”.

By default enctype is “application/x-www-form-urlencoded”. This is fine for normal use so you don’t normally have to set it explicitly. However we’re uploading a file and so we need to use “multipart/form-data”.

<input type="hidden" name="MAX_FILE_SIZE" value="2500" />

This field is not necessary. The PHP documentation used to state that this line of code would enable the browser to check whether the file exceeded the size limit before it was uploaded. This has never been implemented by any browser but is still a “fact” which is repeated in numerous websites and books. The only real use for it is that PHP will throw a different error if the file exceeds this size than it will if the file exceeds to maximum size set in php.ini. It’s recommended that you don’t use this at all as it can easily be changed by the client, making it a far from flawless system. Instead, check the file size using a conventional php script (see below). See here for more information.

<input type="file" name="myfile" />

This is the text box that shows the selected file’s address and the button that is used to browse for a file.

Then there’s a submit button. I’ll let you figure out what that does.

The PHP page.

$target_path = "images/" . basename($_FILES['uploadedfile']['name']);
if ($_FILES["myfile"]["size"] > 25000) {
    echo "The file was too big.";
} else if (($_FILES['file']['type'] <> 'image/gif') && ($_FILES['file']['type'] <> 'image/jpeg') && ($_FILES['file']['type'] <> 'image/pjpeg')){
    echo 'Inappropriate file type.';
} else {
    if(move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path)) {
        echo 'The file '.basename( $_FILES['myfile']['name']).' has been uploaded';
    } else{
        echo 'There was an error uploading the file, please try again!';

Once again, with feeling explanations.

$target_path = 'images/' . basename($_FILES['myfile']['name']);

At this point in the code our file is stored in a temporary directory. When our script finishes the file will be deleted so we need to copy it to somewhere appropriate.

The line above creates a variable which holds a combination of the final destination directory (‘images/’) and the image’s filename (i.e. a full url). The basename function strips out the directory information and returns just the filename and extension. If we then join this with the directory we want to put it we have a full and correct address for it.

The “[‘myfile’]” refers to the name parameter of the file input tag in the form of the html page.

if ($_FILES['myfile']['size'] > 25000) {
    echo 'The file was too big.'

This line checks the size of the uploaded file. If it’s too big we write out an error message and do nothing else.

} else if (($_FILES['file']['type'] <> 'image/gif') && ($_FILES['file']['type'] <> 'image/jpeg') && ($_FILES['file']['type'] && 'image/pjpeg")){
    echo 'Inappropriate file type.';

Now we check the file types. If the file type is not a gif or jpg then we throw an error.

if(move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path)) {
    echo 'The file '.basename( $_FILES['myfile']['name']).' has been uploaded';

If we get this far then all of our checks must have been passed, so this file is ok to keep. This means we need to move it to the appropriate place. We put this command within an IF statement so that we can deal with the result easily. We use the move_uploaded_file() function to move the file. We pass it two parameters: “$_FILES[myfile’][‘tmp_name’]” is an alias for the uploaded file as it exists in the temporary folder. The “$target_path” we created way back at the beginning of the php code and contains the location that the file should end up.

If the uploaded file is a valid file and is moved successfully then the move_uploaded_file() function returns True, in which case we spit out a confirmation or, if false is returned spit out an error.

The above code is pretty basic. It’ll get your file uploaded but you might want to put some more checks in to make sure you’re only allowing them to upload what you want them to upload. Also it will overwrite any files with the same name, so you should check that first as well. Enjoy!


About Mr Chimp

I make music, draw pictures, browse the internet, programme, and make sweet, sweet cups of tea until the early hours.
This entry was posted in Programming and tagged , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s