-1

I am trying to set the background of the html body dynamically. Basically if a file exists, use it, otherwise use the default. But it keeps using the default regardless of whether the file exists or not.

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

I have tried using the file (the commented line) and it works. I can not see why this doesn't work

Tom Hanson
  • 873
  • 10
  • 39
  • 1
    The browser will treat `/profile_img/...` as a relative path, while server-side PHP is treating it as absolute. – Daniel Abercrombie Jul 14 '18 at 03:34
  • Sorta. The browser treats `/profile_img` as absolute to the hostname (so basically the web root) while the server treats it as absolute to the system root directory. So `file_exists("./profile_img/")` is probably what you want for checking for the file at the webroot. – Anthony Jul 14 '18 at 03:54

1 Answers1

2

Some issues:

  • Using / will be absolute, causing it to look in the root directory.
  • Always check vars are set before using.
  • All that's changing is the filename, so you can use a ternary, which will reduce alot of that code.
<?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>

If it's still not working:

  • Check the file actually exists.
Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106