PHP检查文件扩展名

问题描述 投票:45回答:7

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

if (FILE EXTENSION == ???)
{
FUNCTION1
}
else if
{
FUNCTION2
}
php
7个回答
97
投票

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

18
投票
$info = pathinfo($pathtofile);
if ($info["extension"] == "jpg") { .... }

3
投票
$file_parts = pathinfo($filename);

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

if (in_array($file_parts['extension'], $cool_extensions)){
    FUNCTION1
} else {
    FUNCTION2
}

3
投票

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

$spl = new SplFileInfo($filename); 
print_r($spl->getExtension()); //gives extension 

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

对于php 5.3+使用finfo

$finfo = new finfo(FILEINFO_MIME);
print_r($finfo->buffer(file_get_contents($file name)); 

1
投票
  $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) ;
   } 

0
投票
$path = 'image.jpg';
echo substr(strrchr($path, "."), 1); //jpg

0
投票
$file=$_FILES["file"] ["tmp_name"]; 
$check_ext=strtolower(pathinfo($file,PATHINFO_EXTENSION) );
If($check_ext=="fileext"){
//code
}
 else{ 
//codes
   }
© www.soinside.com 2019 - 2024. All rights reserved.