【问题标题】:PHP file_exists method not working as expectedPHP file_exists 方法未按预期工作
【发布时间】:2018-12-22 09:53:48
【问题描述】:

我正在尝试动态设置 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>

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

【问题讨论】:

  • 浏览器会将/profile_img/...视为相对路径,而服务器端PHP将其视为绝对路径。
  • 排序。浏览器将/profile_img 视为绝对主机名(因此基本上是Web 根目录),而服务器将其视为绝对系统根目录。所以 file_exists("./profile_img/") 可能是您在 webroot 上检查文件时想要的。

标签: php html file-exists


【解决方案1】:

一些问题:

  • 使用/ 将是绝对的,导致它在根目录中查找。
  • 使用前请务必检查变量是否已设置。
  • 改变的只是文件名,因此您可以使用三元组,这将减少大量代码。
<?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>

如果还是不行:

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

【讨论】:

  • 很好地使用微时间。
猜你喜欢
  • 2015-05-07
  • 1970-01-01
  • 2019-04-22
  • 2015-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-07
  • 2020-10-04
相关资源
最近更新 更多