如何在 PHP 中获取文件扩展名?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/173868/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 21:47:19  来源:igfitidea点击:

How do I get a file extension in PHP?

phpfile-extension

提问by e-satis

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', '', $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.

然而,总是有“最好的方法”,它应该在 Stack Overflow 上。

回答by e-satis

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 :-)).

来自其他脚本语言的人总是认为他们的更好,因为他们有一个内置的函数来做到这一点,而不是 PHP(我现在正在看 Pythonistas :-))。

In fact, it does exist, but few people know it. Meet pathinfo():

事实上,它确实存在,但很少有人知道。见面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.

这是快速和内置的。pathinfo()可以为您提供其他信息,例如规范路径,具体取决于您传递给它的常量。

Remember that if you want to be able to deal with non ASCII characters, you need to set the locale first. E.G:

请记住,如果您希望能够处理非 ASCII 字符,则需要先设置语言环境。例如:

setlocale(LC_ALL,'en_US.UTF-8');

Also, note this doesn't take into consideration the file content or mime-type, you only get the extension. But it's what you asked for.

另外,请注意这不考虑文件内容或 mime 类型,您只能获得扩展名。但这是你要求的。

Lastly, note that this works only for a file path, not a URL resources path, which is covered using PARSE_URL.

最后,请注意,这仅适用于文件路径,而不适用于使用 PARSE_URL 涵盖的 URL 资源路径。

Enjoy

享受

回答by Adam Wright

pathinfo()

pathinfo()

$path_info = pathinfo('/foo/bar/baz.bill');

echo $path_info['extension']; // "bill"

回答by T.Todua

Example URL: http://example.com/myfolder/sympony.mp3?a=1&b=2#XYZ

示例网址: http://example.com/myfolder/sympony.mp3?a=1&b=2#XYZ

A) Don't use suggested unsafe PATHINFO:

A)不要使用建议的 unsafePATHINFO

pathinfo($url)['dirname']    'http://example.com/myfolder'
pathinfo($url)['basename']   'sympony.mp3?a=1&b=2#XYZ'         // <------- BAD !!
pathinfo($url)['extension']  'mp3?a=1&b=2#XYZ'                 // <------- BAD !!
pathinfo($url)['filename']   'sympony'

B) Use PARSE_URL:

B) 使用PARSE_URL

parse_url($url)['scheme']    'http'
parse_url($url)['host']      'example.com'
parse_url($url)['path']      '/myfolder/sympony.mp3'
parse_url($url)['query']     'aa=1&bb=2'
parse_url($url)['fragment']  'XYZ'


BONUS: View all native PHP examples

奖励:查看所有原生 PHP 示例

回答by hakre

There is also SplFileInfo:

还有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:

如果传递这样的对象而不是字符串,通常可以编写更好的代码。你的代码更会说话。从 PHP 5.4 开始,这是一个单行:

$ext  = (new SplFileInfo($path))->getExtension();

回答by Toxygene

E-satis's response is the correct way to determine the file extension.

E-satis 的响应是确定文件扩展名的正确方法。

Alternatively, instead of relying on a files extension, you could use the fileinfoto determine the files MIME type.

或者,您可以使用fileinfo来确定文件的 MIME 类型,而不是依赖文件扩展名。

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;
}

回答by Anonymous

As long as it does not contain a path you can also use:

只要它不包含路径,您也可以使用:

array_pop(explode('.', $fname))

Where $fnameis a name of the file, for example: my_picture.jpg. And the outcome would be: jpg

$fname文件名在哪里,例如:my_picture.jpg. 结果将是:jpg

回答by Alix Axel

Sometimes it's useful to not to use pathinfo($path, PATHINFO_EXTENSION). For example:

有时不使用pathinfo($path, PATHINFO_EXTENSION). 例如:

$path = '/path/to/file.tar.gz';

echo ltrim(strstr($path, '.'), '.'); // tar.gz
echo pathinfo($path, PATHINFO_EXTENSION); // gz

Also note that pathinfofails 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.

另请注意,pathinfo无法处理一些非 ASCII 字符(通常它只是从输出中抑制它们)。在通常不是问题的扩展中,但意识到这一警告并没有什么坏处。

回答by Subodh Ghulaxe

1)If you are using (PHP 5 >= 5.3.6)you can use SplFileInfo::getExtension— Gets the file extension

1)如果您正在使用(PHP 5 >= 5.3.6)您可以使用SplFileInfo::getExtension— 获取文件扩展名

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

2)如果您正在使用(PHP 4 >= 4.0.3, PHP 5),另一种获取扩展的方法是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

// 编辑:删除了一个括号

回答by Shahbaz

The simplest way to get file extension in PHP is to use PHP's built-in function pathinfo.

在 PHP 中获取文件扩展名的最简单方法是使用 PHP 的内置函数pathinfo

$file_ext = pathinfo('your_file_name_here', PATHINFO_EXTENSION);
echo ($file_ext); // The output should be the extension of the file e.g., png, gif, or html

回答by pooya_sabramooz

You can try also this (it works on PHP 5.* and 7):

你也可以试试这个(它适用于 PHP 5.* 和 7):

$info = new SplFileInfo('test.zip');
echo $info->getExtension(); // ----- Output -----> zip

Tip: it returns an empty string if the file doesn't have an extension

提示:如果文件没有扩展名,它将返回一个空字符串