使用pathinfo()时无法获取文件扩展名


Failing to get file extension when using pathinfo()

我正在为一个照片网站构建一个上传器,上传的大多数照片的类型都是1232132_1231_12.jpg。当我运行pathinfo()时,我会得到空白的扩展输出。

这是我的代码

$target_dir = "Photos/";
$species =  filter_input(INPUT_POST, 'species');
$country =  filter_input(INPUT_POST, 'country');
$type= filter_input(INPUT_POST, 'type');
include_once 'connection.php';
echo $target_dir . basename($_FILES["file"]["name"]);
for($a=0;$a<count($_FILES['file']['tmp_name']);$a++)
{
$target_file = $target_dir . basename($_FILES["file"]["name"][$a]);
$imageFileType=pathinfo($target_file, PATHINFO_EXTENSION);
var_dump(pathinfo($target_file));
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" )
    {
       echo "<br> Sorry, only JPG, JPEG, PNG & GIF files are allowed. your file is a  $imageFileType <br>";
    } 
}

照片/2014-02-21 18.19.08.jpg

 echo $target-file;

给出此输出Photos/2014-02-21 18.19.08.jpg

对于var_ dump,array(3){["dirname"]=>string(6)"Photos"["basename"]=>string(1)"2"["filename"]=>字符串(1)"2"}

我的代码有问题吗?或者pathinfo()不能很好地处理数字和特殊字符的文件名吗?

是否有其他函数可以处理这些类型的文件名,或者应该用"."来解释$target_file()并获取返回数组中的最后一个元素?

问题不是路径信息。你在做一些奇怪的事情:

$target_file = $target_dir . basename($_FILES["file"]["name"][$a]);

这一行在$a介于0和…之间的循环中。。。$_FILES["file"]["name"]正在返回文件名。但是:

$_FILES["file"]["name"][0]

将返回文件名中的第一个字母(例如2)。所以,你正在对你的变量做一个路径信息:

$target_file = $target_dir . basename($_FILES["file"]["name"][$a]); // looks like $target_file = Photos/2 (when $a = 0)

把那条线改成这样:

$target_file = $target_dir . basename($_FILES["file"]["name"]);

对我来说,这个有效:

    function convertImageToWebP($source, $destination, $quality=80) {
    if (exif_imagetype($source) == IMAGETYPE_GIF) { $image = imagecreatefromgif($source); }
elseif (exif_imagetype($source) == IMAGETYPE_JPEG) { $image = imagecreatefromjpeg($source); }
elseif (exif_imagetype($source) == IMAGETYPE_PNG) { $image = imagecreatefrompng($source); }
    return imagewebp($image, $destination, $quality);
}

我希望它能解决:-)