如何在 PHP 中获取(提取)文件扩展名?
This is a question you can read everywhere on the web with various answers :
$ext = end(explode('.', $filename));
$ext = substr(strrchr($filename, '.'), 1);
$ext = substr($filename, strrpos($filename, '.') + 1);
$ext = preg_replace('/^.*\.([^.]+)$/D', '$1', $filename);
$exts = split("[/\\.]", $filename);
$n = count($exts)-1;
$ext = $exts[$n];
etc.
However, there is always "the best way" and it should be on Stack Overflow.
转载于:https://stackoverflow.com/questions/173868/how-to-getextract-a-file-extension-in-php
People from other scripting languages always think theirs is better because they have a built in function to do that and not PHP (I am looking at pythonistas right now :-)).
In fact, it does exist, but few people know it. Meet pathinfo()
:
$ext = pathinfo($filename, PATHINFO_EXTENSION);
This is fast and built-in. pathinfo()
can give you other information, such as canonical path, depending on the constant you pass to it.
Remember that if you want to be able to deal with non ASCII characters, you need to set the locale first. E.G:
setlocale(LC_ALL,'en_US.UTF-8');
Also note this doesn't take in consideration the file content or mimetype, you only get the extension. But it's what you asked for.
Lastly, note that this works only for a file path, not a URL ressources path, which are covered using PARSE_URL.
Enjoy
E-satis response is the correct way to determine the file extension.
Alternatively, instead of relying on a files extension, you could use the fileinfo (http://us2.php.net/fileinfo) to determine the files MIME type.
Here's a simplified example of processing an image uploaded by a user:
// Code assumes necessary extensions are installed and a successful file upload has already occurred
// Create a FileInfo object
$finfo = new FileInfo(null, '/path/to/magic/file');
// Determine the MIME type of the uploaded file
switch ($finfo->file($_FILES['image']['tmp_name'], FILEINFO_MIME)) {
case 'image/jpg':
$im = imagecreatefromjpeg($_FILES['image']['tmp_name']);
break;
case 'image/png':
$im = imagecreatefrompng($_FILES['image']['tmp_name']);
break;
case 'image/gif':
$im = imagecreatefromgif($_FILES['image']['tmp_name']);
break;
}
As long as it does not contain path you can also use:
array_pop(explode('.',$fname))
Where $fname
is a name of the file, for example: my_picture.jpg
And the outcome would be: jpg
There is also SplFileInfo
:
$file = new SplFileInfo($path);
$ext = $file->getExtension();
Often you can write better code if you pass such an object around instead of a string, your code is more speaking then. Since PHP 5.4 this is a one-liner:
$ext = (new SplFileInfo($path))->getExtension();
Sometimes it's useful to not to use pathinfo($path, PATHINFO_EXTENSION)
, for example:
$path = '/path/to/file.tar.gz';
echo ltrim(strstr($path, '.'), '.'); // tar.gz
echo pathinfo($path, PATHINFO_EXTENSION); // gz
Also note that pathinfo
fails to handle some non-ASCII characters (usually it just suppresses them from the output), in extensions that usually isn't a problem but it doesn't hurt to be aware of that caveat.
Use
str_replace('.', '', strrchr($file_name, '.'))
for a quick extension retrieval (if you know for sure your file name has one).
substr($path, strrpos($path, '.') + 1);
1) If you are using (PHP 5 >= 5.3.6) you can use SplFileInfo::getExtension — Gets the file extension
Example code
<?php
$info = new SplFileInfo('test.png');
var_dump($info->getExtension());
$info = new SplFileInfo('test.tar.gz');
var_dump($info->getExtension());
?>
This will output
string(3) "png"
string(2) "gz"
2) Another way of getting the extension if you are using (PHP 4 >= 4.0.3, PHP 5) is pathinfo
Example code
<?php
$ext = pathinfo('test.png', PATHINFO_EXTENSION);
var_dump($ext);
$ext = pathinfo('test.tar.gz', PATHINFO_EXTENSION);
var_dump($ext);
?>
This will output
string(3) "png"
string(2) "gz"
// EDIT: removed a bracket
This will work
$ext = pathinfo($filename, PATHINFO_EXTENSION);
I found that the pathinfo()
and SplFileInfo
solutions works well for standard files on the local file system, but you can run into difficulties if you're working with remote files as URLs for valid images may have a #
(fragment identifiers) and/or ?
(query parameters) at the end of the URL, which both those solutions will (incorrect) treat as part of the file extension.
I found this was a reliable way to use pathinfo()
on a URL after first parsing it to strip out the unnecessary clutter after the file extension:
$url_components = parse_url($url); // First parse the URL
$url_path = $url_components['path']; // Then get the path component
$ext = pathinfo($url_path, PATHINFO_EXTENSION); // Then use pathinfo()
Here is a example, suppose $filename is "example.txt"
$ext = substr($filename,strrpos($filename,'.',-1),strlen($filename));
So $ext will be ".txt"
The simplest way to get file extension in php is to use php built-in function pathinfo.
$file_ext = pathinfo('your_file_name_here', PATHINFO_EXTENSION);
echo ($file_ext); // the out should be extension of file eg:-png, gif, html
A quick fix would be something like this.
//exploding the file based on . operator
$file_ext = explode('.',$filename);
//count taken (if more than one . exist; files like abc.fff.2013.pdf
$file_ext_count=count($file_ext);
//minus 1 to make the offset correct
$cnt=$file_ext_count-1;
// the variable will have a value pdf as per the sample file name mentioned above.
$file_extension= $file_ext[$cnt];
You can get all file extension on particular folder and do operation with specific file extention
<?php
$files=glob("abc/*.*");//abc is folder all files inside folder
//print_r($files);
//echo count($files);
for($i=0;$i<count($files);$i++):
$extension = pathinfo($files[$i], PATHINFO_EXTENSION);
$ext[]=$extension;
//do operation for perticular extenstion type
if($extension=='html'){
//do operation
}
endfor;
print_r($ext);
?>
you can try also this :
pathinfo(basename( $_FILES["fileToUpload"]["name"]),PATHINFO_EXTENSION)
pathinfo is array. We can check directory name,file name,extension etc
$path_parts = pathinfo('test.png');
echo $path_parts['extension'], "\n";
echo $path_parts['dirname'], "\n";
echo $path_parts['basename'], "\n";
echo $path_parts['filename'], "\n";
If you are looking for speed (such as in a router), you probably don't want to tokenize everything. Many other answers will fail with /root/my.folder/my.css
ltrim(strrchr($PATH, '.'),'.');
Why not to use substr($path, strrpos($path,'.')+1);
?
It is the fastest method of all compare.
@Kurt Zhong already answered.
Let's check the comparative result here: https://eval.in/661574
you can try also this
(work on php 5.* and 7)
$info = new SplFileInfo('test.zip');
echo $info->getExtension(); // ----- Output -----> zip
tip: it return an empty string if the file has no extension
enjoy it ;)
Although the "best way" is debatable, I believe this is the best way for a few reasons:
function getExt($path)
{
$basename = basename($path);
return substr($basename, strlen(explode('.', $basename)[0]) + 1);
}
- It works with multiple parts to an extension, eg
tar.gz
- Short and efficient code
- It works with both a filename and a complete path