Search code examples
phphtmlfile-exists

PHP file_exists method not working as expected


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


Solution

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