DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Chara has posted 51 posts at DZone. View Full User Profile

Get File Extension in PHP

11.04.2012
| 6324 views |
  • submit to reddit
    <?php
/* Source: http://www.apphp.com/index.php?snippet=php-get-file-extension */
    function get_file_extension($file_name)
    {
        /* may contain multiple dots */
        $string_parts = explode('.', $file_name);
        $extension = $string_parts[count($string_parts) - 1];
        $extension = strtolower($extension);
        return $extension;
    }
    ?>

This code allows to pass filename in the $file_name variable and function will return file extension only.

Comments

Anush Anil Kumar replied on Sun, 2012/12/23 - 2:57am

Here is another code using end() function 

$file_ext=strtolower(end(explode('.',$_FILES['image']['name'])));      

its more safer that using count($string_parts) - 1, when the file name has a dot in it it will make problems.

More details explained here http://techstream.org/Web-Development/PHP/Single-File-Upload-With-PHP