The file extension is very useful for validation and upload. You can easily get extension from the file name or file location using PHP. In this tutorial, we will show you two simple way to get file extension in PHP.
The get_file_extension() function returns extension of the file using substr()
and strrchr()
in PHP.
function get_file_extension($file_name) {
return substr(strrchr($file_name,'.'),1);
}
Usage
You need to pass the filename in get_file_extension()
, it will return the extension of the given file.
echo get_file_extension('image.jpg');
The pathinfo()
function provides the easiest way to get file information in PHP.
Usage
The file path needs to be passed in pathinfo()
, it will return the information (directory name, base file name, extension, and filename) of the given file.
$path_parts = pathinfo('files/codexworld.pdf');
//file directory name
$directoryName = $path_parts['dirname'];
//base file name
$baseFileName = $path_parts['basename'];
//file extension
$fileExtension = $path_parts['extension'];
//file name
$fileName = $path_parts['filename'];