Find file extension in PHP

0
80
Sending Emails in PHP
Prestashop 1.5 features for developers (Part-1 Modules)

In this article we will be studying how to find file extension in php. While coding in php or any other programming languages and dealing with the files, we may need to find out the file extension. There are several ways to find file extension in php. Some of the links for some sites are below:

http://cowburn.info/2008/01/13/get-file-extension-comparison/

http://php.about.com/od/finishedphp1/qt/file_ext_PHP.htm

One of the easiest way to find file extension in php is just a simple two line code. Consider the following code


<?php

//Explode the file name with "."
$explode = explode(".", $fileName);

//Get the end array entery, and that is the file extension
$extension = end($explode);

?>

You may know that the file extension in a file name is always at the end of the full file name and is separated from the file name by a dot (.). So first we need to explode the full file name by dot(.) which is done at line 4 in the above code.

Now as we know the explode function returns an array of strings which are all part of the exploded strings. As we mentioned above, the file extension is at the end of the full file name separated by a dot(.) from the file name, so the $explode array has the extension at the end of the array or the extension of the file is the last item of the $explode array.

Now we need to get that last item of the $explode array, which is done at line 7 using end function. What the end function do? the end function returns the last item of the target array and thats it. SO at line 7, the code returns the last item of the $explode array which is our desired file extension.

How easy that is to find file extension in php 🙂 .

Sending Emails in PHP
Prestashop 1.5 features for developers (Part-1 Modules)

Leave a Reply