php 如何在PHP中获取文件扩展名?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10368217/
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
How to get the file extension in PHP?
提问by Keith Power
I wish to get the file extension of an image I am uploading, but I just get an array back.
我希望获得我正在上传的图像的文件扩展名,但我只是获得了一个数组。
$userfile_name = $_FILES['image']['name'];
$userfile_extn = explode(".", strtolower($_FILES['image']['name']));
Is there a way to just get the extension itself?
有没有办法只获得扩展本身?
回答by ThiefMaster
No need to use string functions. You can use something that's actually designed for what you want: pathinfo():
无需使用字符串函数。您可以使用实际为您想要的东西设计的东西pathinfo()::
$path = $_FILES['image']['name'];
$ext = pathinfo($path, PATHINFO_EXTENSION);
回答by Andrey
This will work as well:
这也将起作用:
$array = explode('.', $_FILES['image']['name']);
$extension = end($array);
回答by Julien
A better method is using strrpos + substr (faster than explode for that) :
更好的方法是使用 strrpos + substr (比爆炸快):
$userfile_name = $_FILES['image']['name'];
$userfile_extn = substr($userfile_name, strrpos($userfile_name, '.')+1);
But, to check the type of a file, using mime_content_type is a better way : http://www.php.net/manual/en/function.mime-content-type.php
但是,要检查文件的类型,使用 mime_content_type 是更好的方法:http://www.php.net/manual/en/function.mime-content-type.php
回答by Balan
You could try with this for mime type
你可以试试这个用于 mime 类型
$image = getimagesize($_FILES['image']['tmp_name']);
$image['mime']will return the mime type.
$image['mime']将返回 MIME 类型。
This function doesn't require GD library. You can find the documentation here.
此功能不需要 GD 库。您可以在此处找到文档。
This returns the mime type of the image.
这将返回图像的 MIME 类型。
Some people use the $_FILES["file"]["type"]but it's not reliable as been given by the browser and not by PHP.
有些人使用 ,$_FILES["file"]["type"]但它不可靠,因为浏览器而不是 PHP 给出的。
You can use pathinfo()as ThiefMaster suggested to retrieve the image extension.
您可以pathinfo()按照 ThiefMaster 的建议使用来检索图像扩展名。
First make sure that the image is being uploaded successfully while in development before performing any operations with the image.
在对图像执行任何操作之前,首先确保图像在开发过程中成功上传。
回答by ilanco
How about
怎么样
$ext = array_pop($userfile_extn);

