How to get file extension using PHP

A simple yet powerful approach to get file extension using PHP. We usually need to extract file extension from file name while uploading file so that we could generate new name and rename file to our convenience. We could create new file name using time, random or hashing, example of which has been given at the last paragraph of this post.

[php]
function get_file_extension($filename) {
return substr($filename, strrpos($filename, ‘.’)+1, strlen($filename)-strrpos(‘.’, $filename));
}[/php]

Explanation:

It uses built-in substring, strrpos and strlen functions to extract file extension. A brief on these functions.

substr — Return part of a string
string substr ( string $string , int $start [, int $length ] )
Returns the portion of string specified by the start and length parameters.

strrpos — Find the position of the last occurrence of a substring in a string
int strrpos ( string $haystack , string $needle [, int $offset = 0 ] )
Returns the numeric position of the last occurrence of needle in the haystack string.

strlen — Get string length
int strlen ( string $string )
Returns the length of the given string.

For getting file extension while making these working in conjunction we use substr to chop file name in such a way that it gives us all characters which occurs after the last occurrence of character dot (.).

Here’s how one could get file extension and create new filename:

[php]
$filename="hello.my_file_name.jpg";
$new_filename = md5(time().random(0, 100000)) . ‘.’ . get_file_extension($filename);
[/php]

Leave a Reply