File Uploads
April 5th, 2006
File uploads are probably one of the things that new coders get worried about, and it is actually very simple. PHP has made vast inroads into supporting file uploads, and you can upload a file with just a few small lines of code.
In this article, I'm going to go through some simple things you should consider when uploading files, and some common mistakes made.
Uploading a file
Uploading a file is very easy. You need to add two things to your form. The first is to provide the correct enctype in the form tag, and the other is to have a file select input box:
<form name="upload" action="upload.php" method="POST" enctype="multipart/form-data">
File: <input type="file" name="upfile">
<input type="submit" name="upload" value="Upload File">
</form>
NB: Its important to note that using the multipart/form-data enctype will mean that you cannot read the form input via the php://input wrapper
Submitting this form will fill the $_POST superglobal variable with the POST variables for this form, but it will also provide us with another superglobal variable that has the information about our file upload: $_FILES. Submitting the form above will give us this information in $_FILES:
Array
(
[upfile] => Array
(
[name] => ben.jpg
[type] => image/jpeg
[tmp_name] => /tmp/php9r8vZs
[error] => 0
[size] => 137368
)
)
Checking the file
Before we move the file to where we want it to reside, it would be advisable to validate that the file we have is one that we would like to have. The first thing to check is our error code. In the above example, the error code is 0, showing that there were no errors experienced. Error code 4 would mean that no file was actually uploaded. A list of error codes can be found in the PHP manual.
Once you are satisfied that the file is actually uploaded, we should check that the file is what we wanted. The size of the uploaded file is limited in several ways. We can define the filesize in our upload form by including a hidden field called MAX_FILE_SIZE and then giving it a value in bytes of the maximum file size. However, this can be easily changed by the user. In the main php configuration file, php.ini, there are several directives that determine how big the file upload can be. By default, the max upload size is limited to 2Mb. If you get error code 1 or 2 on your upload, then this is because the file that is being uploaded is too big.
We should also be checking the type of file uploaded. In the above example, the type is given as image/jpeg. However, if I rename my picture to ben.png, the image mime type is given as image/png. The mime type in the $_FILES array is the mime type submitted by the user's browser. Thus, if I was to rename bad_virus.exe to bad_virus.jpg, it would appear as image/jpeg, and not application/octet-stream. The only correct way of determining the type of file uploaded is by inspecting the file's header and determining it using the aid of libmagic. This can be done in PHP by using the fileinfo extension. However, this is not usually available in stock versions of PHP available on webservers, and so most people are fairly limited to what they can do. You can double check the reported mime type against the extension and ensure that they match. You could do this with the aid of a nice big array of all the major mime types.
Saving our file
When our file is uploaded, it is first placed in a temporary directory and given a temporary filename, usually /tmp. In our above example, the location and filename of our uploaded file is /tmp/php9r8vZs. We need to save this file in another directory before the page has finished loading. If the upload script stops executing before the file is moved, the uploaded file is deleted. There are two ways of saving this file: either by copy() or with move_uploaded_file(). The correct method is to use move_uploaded_file. This is because is safe_mode and/or open_basedir are enabled in the main php configuration, copy() will fail, whereas move_uploaded_file() will be allowed to proceed. To move the file, we simply use this:
-
move_uploaded_file($_FILES['upfile']['tmp_name'],'/home/username/public_html/uploads/filename.jpg');
You will need to ensure that the webserver has the correct write permissions for the 'uploads/' directory, usually set to 777 for most shared webservers.
Uploading Multiple Files
Most times, you will want to upload more than one file. This can be done by adding another file select input field, and naming it differently to your original. This may seem the logical way, however, I've always found it easier to name the input fields all the same, and append '[]' to the name, thus making PHP turn them into an array once processed:
<form name="upload" action="upload.php" method="POST" enctype="multipart/form-data">
File: <input type="file" name="upfile[]">
File: <input type="file" name="upfile[]">
<input type="submit" name="upload" value="Upload File">
</form>
And once submitted:
Array
(
[upfile] => Array
(
[name] => Array
(
[0] => 100_0070.jpg
[1] => 100_0200.JPG
)
[type] => Array
(
[0] => image/jpeg
[1] => image/jpeg
)
[tmp_name] => Array
(
[0] => /tmp/php3M3GeL
[1] => /tmp/php9JCxkq
)
[error] => Array
(
[0] => 0
[1] => 0
)
[size] => Array
(
[0] => 773770
[1] => 485147
)
)
)
Thus, to go through each file:
More?
Although we've covered the basics, there is plenty more that can be discussed. For instance, move_uploaded_file() will overwrite the destination filename if it already exists, so we should check for that if needed. How about virus checking the uploaded file? Or giving it a randomly generated filename? I'll cover those soon...
Add to del.icio.us
Digg this
Technorati
Related Posts:
- Using DirectoryIterator to List Files in PHP
- PHP, Mime Types and Fileinfo
- PHP, cURL, HTTP PUT, SSL and Basic Authentication
- Raw POST Data in PHP
- 301 Page Redirects using PHP and .htaccess
Entry Filed under: PHP
3 Comments Add your own
1. PHPAvançado&hellip | April 6th, 2006 at 1:17 pm
Upload de Arquivos…Ontem eu estava pensando em escrever um artigo bem detalhado de como fazer upload, pois o pessoal tem procurado bastante por isso…Só que hoje eu achei um tutorial em inglês com tudo explicadinho com todo passo-a-passo… mesmo que você não saqu…
2. Webdesiigner | April 11th, 2006 at 4:57 pm
Muito bom, para leigos é um tutorial execelente
3. halmeida | April 12th, 2007 at 10:59 am
Gostaria que houvesse um login e senha pra que fosse possivel controlar quem faz upload..
Só fazer upload tem varios.Mas ninguem colocar senha neles.
se alguem conseguir fazer um completo seria legal.
valeu!
Leave a Comment
Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>
Trackback this post | Subscribe to the comments via RSS Feed