PHP检查文件扩展名

use*_*794 46 php

我有一个上传脚本,我需要检查文件扩展名,然后根据该文件扩展名运行单独的函数.有人知道我应该使用什么代码吗?

if (FILE EXTENSION == ???)
{
FUNCTION1
}
else if
{
FUNCTION2
}
Run Code Online (Sandbox Code Playgroud)

Bro*_*omb 101

pathinfo 是你在找什么

PHP.net

$file_parts = pathinfo($filename);

switch($file_parts['extension'])
{
    case "jpg":
    break;

    case "exe":
    break;

    case "": // Handle file extension for files ending in '.'
    case NULL: // Handle no file extension
    break;
}
Run Code Online (Sandbox Code Playgroud)

  • 更新.空字符串`""`用于文件,然后以`.`结尾.`NULL`表示没有文件扩展名.你可以打破case语句,但是对于这个例子我只是将它们组合在一起. (2认同)

Alo*_*tan 18

$info = pathinfo($pathtofile);
if ($info["extension"] == "jpg") { .... }
Run Code Online (Sandbox Code Playgroud)


Aki*_*imi 6

对于 php,5.3+您可以使用SplFileInfo()该类

$spl = new SplFileInfo($filename); 
print_r($spl->getExtension()); //gives extension 
Run Code Online (Sandbox Code Playgroud)

此外,由于您正在检查文件上传的扩展名,我强烈建议您使用 mime 类型代替..

对于 php5.3+使用finfo

$finfo = new finfo(FILEINFO_MIME);
print_r($finfo->buffer(file_get_contents($file name)); 
Run Code Online (Sandbox Code Playgroud)


小智 5

$file_parts = pathinfo($filename);

$file_parts['extension'];
$cool_extensions = Array('jpg','png');

if (in_array($file_parts['extension'], $cool_extensions)){
    FUNCTION1
} else {
    FUNCTION2
}
Run Code Online (Sandbox Code Playgroud)