Get file extension php upload
Sometimes we want to check the extension first before placing it onto our server.
This could be to ensure safety or just to avoid problems reading the file later on.
For whatever reason it's important that this is done correctly. We can go about doing this in a few ways. Although I don't recommend using substr to fetch the extension due to varying extension lenghts.
The best way would be to fetch the entire part after the dot.
In the following example we do just that:
$filename = $_FILES['files']['name'] // original filename
$extension = end(explode(".", $filename));
You can see we first load the orginal filename which is always stored in the superglobal FILES attribute tmp_name into a string called filename.
Secondly we explode the filename string and store the last part ( holding the entire extension ) into the string called extension.
We split the string into pieces by cutting where dots are present.
Because explode turns the string into an Array we can call the last item of the array with the function end().
The last item of the array will always be the extension because this is the filename. There you have it the extension is now stored in the string extension.
We could perform a check on it now for example :
$filename = $_FILES['files']['tmp_name'] // original filename
$extension = end(explode(".", $filename));
if($extension == 'gif')
{
echo 'The file is an gif. Good!';
}
else
{
echo 'Too bad the file is not a gif file!';
}
In this example we check to see if the extension was gif or not. Of course you can check on any other match or even mutiple matches because sometimes you want to allow gif, png and jpg files.
Sidenote : It's important to note that even though the extension is correct there still is a little safety issue.
For example a gif file in our example can contain javascript code and be executed in this example :
<script src="image.gif" type="text/javascript" />Therefore it's also recommended to check the files contents.
Posted by James on 2009-05-05 in the category " php "
