Thursday, April 23, 2009

Get file extension in PHP

Here are some simple ways to retrieve extension of a file using PHP. You need this when you try to validate file uploads, for example.

So here is one simple way:

$extension = end(explode(".", $filename ));

Let's say we have: $filename = 'text.jpg' then the result will be jpg.

Another way of getting file extension is using pathinfo() function:
$fileinfo = pathinfo($filename);
$extension = $fileinfo['extension'];

And the third way:
$extension = substr(strrchr($filename,'.'),1);

I use the first method, works just fine. You can use what method you want to determine a file extension.

No comments: