Summary of N methods for getting file extensions in PHP

  • 2020-05-12 02:23:17
  • OfStack

Method 1:
 
function get_extension($file) 
{ 
substr(strrchr($file, '.'), 1); 
} 

Method 2:
 
function get_extension($file) 
{ 
return substr($file, strrpos($file, '.')+1); 
} 

The third method:
 
function get_extension($file) 
{ 
return end(explode('.', $file)); 
} 

The fourth method:
 
function get_extension($file) 
{ 
$info = pathinfo($file); 
return $info['extension']; 
} 

Method 5:
 
function get_extension($file) 
{ 
return pathinfo($file, PATHINFO_EXTENSION); 
} 

It seems that all the above methods can be used, especially 1 or 2 methods. Before I know that pathinfo has the second parameter, 1 is also used. But on second thought, the first four methods have all sorts of flaws. To get the file's extension exactly right, you must be able to handle three special cases.
No file extensions
Path contains characters. Such as/home/test d/test txt
The path contains the character., but the file has no extension. Such as/home test d/test
It's obvious: 1, 2 can't handle the third case, and 3 can't handle the 13th case correctly. 4 is handled correctly, but a warning is issued when no extension exists. Only the fifth method is the most correct method. Look at the pathinfo method, by the way. The official website is as follows:
$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+
It will return an array containing up to 4 elements, but it will not have 4 elements directly. For example, if there is no extension, there will be no extension element, so the fourth method will find the warning. But phpinfo also supports the second parameter. You can pass 1 constant, specifying the data to be returned in part 1:
PATHINFO_DIRNAME - directory
PATHINFO_BASENAME - file name (with extension)
PATHINFO_EXTENSION - extension
PATHINFO_FILENAME - file name (without extension, PHP) > 5.2)
The values of these four constants are 1, 2, 4, and 8 respectively. At first, I thought I could specify more than one by or operation:
pathinfo($file, PATHINFO_EXTENSION | PATHINFO_FILENAME);
It turns out that this doesn't work, that it only returns the smallest of several or constants. Which is the constant of the smallest of the four flag bits being 1.
Here are some ways to supplement it
1, php explode function
 
$pic = 'abc.php'; 
$pics = explode('.' , $pic); 
echo $num = count($pics); 
echo '<br>'.$pics[$num-1]; 


So you can output it
. php.

Let's use foreach
 
foreach ($pics as $value) //2 
{ 
$a = $value; 
} 
echo $a.'<br>'; 


There is a good function end which I recommend to use as a shortcut end function
 
echo end($pics); 
echo '<br>'; 


Other access methods can be judged when the file is uploaded, but we cannot use $_FILES without uploading the file.

Related articles: