Validating File Extensions using PHP

A note from A Beautiful Site’s founder: We developed Surreal to be easy for you and your clients. If you’re a web designer, you should take a look at the simple, hosted CMS that’s changing the way content is managed. Surreal integrates in moments and is trusted by over 18,000 websites. Try it out for free and let us know what you think! Visit Website »

A PHP function for validating file extensions.

check_extension()

Takes a string filename and checks it for a valid extension provided in $allowed.

Parameters

Argument Type Explanation
$filename String The filename (with or without path) to be checked
$allowed String/Array A string or array containing the list of extensions that are acceptable
$case_sensitive Boolean Determines whether or not file extensions are matched in a case sensitive manner (default = false)

Return Values

Returns true if allowed, false otherwise.

Code

function check_extension($filename, $allowed = array(), $case_sensitive = false) {
    // Make sure $allowed is always an array
    if( !is_array($allowed) ) $allowed = array($allowed);

    // Determine file extension
    $file_ext = preg_replace('/^.*\./', '', $filename);

    // Handle case sensitivity
    if( !$case_sensitive ) {
        // Convert all allowed to lowercase
        foreach( array_keys($allowed) as $key ) {
            $allowed[$key] = strtolower($allowed[$key]);
        }
        // Convert file extension
        $file_ext = strtolower($file_ext);
    }

    // Check for match
    if( in_array( $file_ext, $allowed ) ) return true; else return false;
}

Example

<?php

// Single extensions example
$filename = "/www/domain/some_file.txt";
$allowed = "txt";
if( check_extension($filename, $allowed) ) echo "TRUE"; else echo "FALSE";

// Multiple extensions example
$filename = "/www/domain/some_file.txt";
$allowed = array("txt", "csv", "dat");
if( check_extension($filename, $allowed) ) echo "TRUE"; else echo "FALSE";

?>
If you enjoyed this article, please share it with a friend!

6 Responses to Validating File Extensions using PHP

  1. What if the filename have more dots:
    like my.photo.gif

    I allways do somethink like this:
    substr($filename, -3)

    Anyway.. good function, i will use it

  2. Cory LaViska says:

    Pablo: substr($filename, -3) will work, but only for 3 letter extensions. A file’s extension is always comprised of all the characters proceeding the last dot (.) in the filename :)

  3. Dan Dean says:

    There are a couple of ways you could make this function more efficient and fool-proof

    1. instead of looping through the array to see if a given extension is in it, just is in_array() : http://us2.php.net/in_array

    2. user regular expressions to find the last set of letters after the last period in the file name:
    $str = “radical.jpg”;
    $matches = null;
    preg_match(‘/\w+$/’,strtolower($str),$matches);
    var_dump($matches[0]);

  4. Cory LaViska says:

    Thanks for the suggestions, Dan. I’ve updated the function using a regular expression to determine the file extension and in_array() instead of looping. I also added an argument to make the comparison case-sensitive or not. Otherwise, the function works exactly the way it used to.

  5. Nima says:

    The dot problem.

    i used pathinfo() instead and changed the code to this:

    function check_extension($filename, $allowed, $case_sensitive = false) {
    $file_ext = pathinfo($filename);
    $ext = $file_ext['extension'];
    if( !$case_sensitive ) {
    foreach( array_keys($allowed) as $key ) {
    $allowed[$key] = strtolower($allowed[$key]);
    }
    $file_ext = strtolower($file_ext);
    }
    if( in_array( $ext, $allowed ) ) return true; else return false;
    }

    now it works even if the filename contains more then one dot.

  6. Nanny Ogg says:

    Hi Nima and Cory,
    Thank you. Your combination of file extension validation code for PHP works beautifully.
    Nanny

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>