Home >Backend Development >PHP Tutorial >How to get file extension in PHP_PHP tutorial
How to get file extension in PHP
There are many ways to obtain file extensions in PHP. Three of them are provided below. You can study them. I won’t explain them in detail. I will give you the final correct answer directly
echo pathinfo('/www/htdocs/your_image.jpg', PATHINFO_EXTENSION);
Incorrect spelling:
You might write like this
function get_file_extension($file_name) {
Return substr(strrchr($file_name,'.'),1);
}
Or write like this
function file_extension($filename) {
Return end(explode(".", $filename));
}
By the way, let’s take a look at what pathinfo does
$file_path = pathinfo('/www/htdocs/your_image.jpg');
echo "$file_path ['dirname']n";
echo "$file_path ['basename']n";
echo "$file_path ['extension']n";
echo "$file_path ['filename']n"; // only in PHP 5.2+
?>
The above will output
/www/htdocs
your_image.jpg
jpg
your_image
, the code is as follows:
//Method 1
function extend_1($file_name)
{
$retval="";
$pt=strrpos($file_name, ".");
if ($pt) $retval=substr($file_name, $pt+1, strlen($file_name) - $pt);
return ($retval);
}
//Method 2
function extend_2($file_name)
{
$extend = pathinfo($file_name);
$extend = strtolower($extend["extension"]);
return $extend;
}
//Method 3
function extend_3($file_name)
{
$extend =explode(".", $file_name);
$va=count($extend)-1;
return $extend[$va];
}
?>