To get the extension of a file in PHP, you can use the pathinfo
function. This function returns an associative array containing information about the path, including the extension.
Here’s an example of how you can use it:
$path = '/path/to/file.txt';
$info = pathinfo($path);
echo $info['extension']; // Outputs: txt
Alternatively, you can also use the substr
function to extract the extension from the file name:
$path = '/path/to/file.txt';
$extension = substr($path, strrpos($path, '.') + 1);
echo $extension; // Outputs: txt
Note that the pathinfo
function is more reliable, as it handles cases where the file name may contain multiple dots (e.g., file.tar.gz
). The substr
method will only return the last part after the last dot, which may not always be the correct extension.