PHP file_exists 方法未按预期工作

PHP file_exists method not working as expected

我正在尝试动态设置 html 正文的背景。基本上,如果文件存在,则使用它,否则使用默认值。但是无论文件是否存在,它都会使用默认值。

<style>
body
{
    padding-top: 50px;
    background-image: url("<?php
    clearstatcache();
    if(file_exists("/profile_img/".$profileData["ID"]."_bg.jpg"))
    {
        echo "/profile_img/".$profileData["ID"]."_bg.jpg?". rand(5, 15);
    }
    else
    {
        //echo "/profile_img/".$profileData["ID"]."_bg.jpg?". rand(5, 15);
        echo "/profile_img/default.jpg?". rand(5, 15);
    }
    ?>");
    background-size: cover;
    background-position: 50% 50%;
}
</style>

我已经尝试使用该文件(注释行)并且它有效。我不明白为什么这不起作用

一些问题:

  • 使用/将是绝对的,导致它在根目录中查找。
  • 使用前务必检查变量是否已设置。
  • 所有改变的只是文件名,所以你可以使用三元,这将减少很多代码。
<?php 
$background = isset($profileData["ID"]) && file_exists('./profile_img/'.$profileData["ID"].'_bg.jpg') 
    ? $profileData["ID"].'_bg.jpg' : 'default.jpg';
?>
<style>
body {
    padding-top: 50px;
    background-image: url("/profile_img/<?= $background.'?_='.microtime(true) ?>");
    background-size: cover;
    background-position: 50% 50%;
}
</style>

如果还是不行:

  • 检查文件是否确实存在。