In this lesson we will find out how to get the file extension of any file in PHP.
Let us consider a file with a name of "myFile.php". We can see that the file extension is php. The question is, how do we retrieve that in PHP?
The first step is to define a string variable with the filename. Obviously, this filename may come from a post variable or database field etc.
We will use a function to retrieve and return the filename extension.
The output would be:
php
The above function will work for filenames where there is only 1 period (.). However, what if the filename is something like "dbconfig.inc.php".
If we use the above script we will get an error like this:
Notice: Array to string conversion in /home/www/file-extension.php on line 9 Array
The reason is that the explode() function is returning an array. If we print out the array we can see what is happening:
The output is:
Array ( [0] => dbconfig [1] => inc [2] => php )
We need to retrieve the end value in this array. Fortunately, PHP has a function to do that. We can use the end() function as follows: