如何使用php获取存储在系统中的文件的扩展名


How to get the extension of a file which is stored in the system using php

我正在尝试检查某个位置是否存在具有特定扩展名的文件名(user_id)。每当我执行它时,只有当部分被执行并且控件不会转到 else if 部分时,即使图像不是 png 扩展名。

$img1 = "../img/profile_imgs/".$user_id.".jpg";
$img2 = "../img/profile_imgs/".$user_id.".png";
$img3 = "../img/profile_imgs/".$user_id.".jpeg";
if (is_bool(file_exists($img1))==1)
{       
    
   echo "am here in jpg";           
   $prof_img =$img_name_jpg;
}
else if (is_bool(file_exists($img2))==1)
{
   echo "am here in png";
   $prof_img =$img_name_png;
}
else if (is_bool(file_exists($img3))==1){
    echo "am here in jpeg";
    $prof_img =$img_name_jpeg;
}

为什么要使用这个复杂的条件:

if (is_bool(file_exists($img1))==1)

这应该可以正常工作:

$img1 = "../img/profile_imgs/".$user_id.".jpg";
$img2 = "../img/profile_imgs/".$user_id.".png";
$img3 = "../img/profile_imgs/".$user_id.".jpeg";
if (file_exists($img1))
{       
    echo "am here in jpg";
    $prof_img = $img_name_jpg;
}
else if (file_exists($img2))
{
    echo "am here in png";
    $prof_img = $img_name_png;
}
else if (file_exists($img3))
{
    echo "am here in jpeg";
    $prof_img = $img_name_jpeg;
}

在你的代码中:

is_bool(file_exists($img1)) == 1

测试file_exists()的结果是否为布尔值,而布尔值始终如此。

也就是说,您可以编写一个小的帮助程序函数,该函数使用要查找的扩展数组为您进行测试:

function filePathMatchingExtensions($path, array $extensions)
{
    foreach ($extensions as $extension) {
        if (file_exists($path . $extension)) {
            return $path . $extension;
        }
    }
    return false;
}
$extensions = ['.jpg', '.jpeg', '.png'];
$prof_img = filePathMatchingExtensions("../img/profile_imgs/$user_id", $extensions);
if ($prof_img !== false) {
    // it exists
} else {
    // it doesn't exist
}
我认为最好

将文件名保留在您的数据库中,而不是尝试猜测文件的扩展名。无论如何,如有必要,您可以尝试@Typoheads回复或函数glob()http://php.net/manual/en/function.glob.php