PHP 检查文件扩展名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7563658/
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
PHP check file extension
提问by user547794
I have an upload script that I need to check the file extension, then run separate functions based on that file extension. Does anybody know what code I should use?
我有一个上传脚本,我需要检查文件扩展名,然后根据该文件扩展名运行单独的函数。有人知道我应该使用什么代码吗?
if (FILE EXTENSION == ???)
{
FUNCTION1
}
else if
{
FUNCTION2
}
回答by Brombomb
回答by Alon Eitan
$info = pathinfo($pathtofile);
if ($info["extension"] == "jpg") { .... }
回答by imaginabit
$file_parts = pathinfo($filename);
$file_parts['extension'];
$cool_extensions = Array('jpg','png');
if (in_array($file_parts['extension'], $cool_extensions)){
FUNCTION1
} else {
FUNCTION2
}
回答by Rotimi
For php 5.3+
you can use the SplFileInfo()
class
对于 php,5.3+
您可以使用SplFileInfo()
该类
$spl = new SplFileInfo($filename);
print_r($spl->getExtension()); //gives extension
Also since you are checking extension for file uploads, I highly recommend using the mime type instead..
此外,由于您正在检查文件上传的扩展名,我强烈建议您改用 mime 类型。
For php 5.3+
use the finfo
class
对于 php5.3+
使用finfo
类
$finfo = new finfo(FILEINFO_MIME);
print_r($finfo->buffer(file_get_contents($file name));
回答by Airy
$path = 'image.jpg';
echo substr(strrchr($path, "."), 1); //jpg
回答by Jasmeen
$original_str="this . is . to . find";
echo "<br/> Position: ". $pos=strrpos($original_str, ".");
$len=strlen($original_str);
if($pos >= 0)
{
echo "<br/> Extension: ". substr($original_str,$pos+1,$len-$pos) ;
}
回答by GeniusGeek
$file=$_FILES["file"] ["tmp_name"];
$check_ext=strtolower(pathinfo($file,PATHINFO_EXTENSION) );
If($check_ext=="fileext"){
//code
}
else{
//codes
}