Advanced file upload handling

To make our upload system a little more advanced, let's take a look at adding a little more security to the system by checking the kind of file just uploaded. It would be great if we could rely on the 'type' information of uploaded files to tell us whether a file is to be accepted or not, but many browsers do not send MIME types with uploaded files. Instead, here is a simple bit of code that checks the extension of an uploaded file - you should recognise explode() already.

    $tmp = explode ( '.', $_FILES['userfile']['name']);
    $fileext = $tmp[count($tmp)-1];

In line one, we split the name of the uploaded file into an array. As we specified a full stop (.) as the first parameter to explode, our array will normally be split into two elements - file name (e.g. 'mysql'), and file extension (e.g. 'rpm'). If our filename was 'php-5.0.0.tar.gz', our array would contain elements 'php-5', '0', '0', 'tar', 'gz'. count() is a new function that merely returns the number of elements in an array, and by subtracting one from it (remember PHP uses zero-based arrays), we find ourselves reading the last element in the array. With php-5.0.0.tar.gz, this would return "gz". With mysql.rpm, this would return "rpm".

Now we can read the extension of the file that was uploaded, let's compare it to a list of extensions we trust.

    $allowedexts = array("rpm", "gz", "tar", "bz2");
    if (in_array($fileext, $allowedexts)) {
        print "File is trusted.";
    } else {
        print "File not trusted!";

In the above code, we create an array of trusted file extensions, then, using in_array(), we compare our $fileext variable (which contains everything after the final full stop in the name of our uploaded text file) to the array of allowed extensions. Naturally, merely checking file extensions does not guarantee security, but every little helps.


Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Checking uploaded files >>

Previous chapter: Handling file uploads

Jump to:


Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.