Search code examples
phpfilenamesfile-exists

PHP file_exists returns false when variable is in file name


I want to check if a jpeg file exists on my server. However, when I check it, the return value is false.

clearstatcache();

// the $img variable is dynamically got from $split[1] which is something like image.jpeg" />
$img = str_replace('"','',$split[1]); // remove double quotes
$img = str_replace('/>','',$img); // remove img end tag
$img = str_replace(' ','',$img); // remove spaces

$filename = "uploads/image.jpeg"; // original file name
$fn = "uploads/".$img; // file name with dynamic variable in it
if(file_exists($fn)){
       echo "yes";
}else{
       echo "no";
}

// Check if the two strings are the same and they are
if($fn == $filename){
       echo "same";
}

The original static file name returns back yes, while the dynamic one gives back no. I checked and safe_mode is off on my server and the two variables ($fn and $filename) are completely the same. If I just simply make $img equal to image.jpeg without any str_replace it also gives back true and echos out yes.
Overall, I do not know what is the problem with the $img variable and why does it give me back two different results, if the variables are the same?


Solution

  • You have some serious flaw in your debugging logic somewhere, try this:

    echo '<hr/>';
    
    clearstatcache();
    
    // the $img variable is dynamically got from $split[1] which is something like image.jpeg" />
    $img = str_replace('"','',$split[1]); // remove double quotes
    $img = str_replace('/>','',$img); // remove img end tag
    $img = str_replace(' ','',$img); // remove spaces
    
    $filename = "uploads/image.jpeg"; // original file name
    $fn = "uploads/".$img; // file name with dynamic variable in it
    if(file_exists($fn)){
        echo '$fn: yes';
        echo '<br/>';
    }else{
        echo '$fn: no';
        echo '<br/>';
    }
    
    if(file_exists($filename)){
        echo '$filename: yes';
        echo '<br/>';
    }else{
        echo '$filename: no';
        echo '<br/>';
    }
    
    // Check if the two strings are the same and they are
    if($fn == $filename){
        echo "same";
        echo '<br/>';
    }
    else
    {
        echo 'different';
        echo '<br/>';
    }
    
    echo '<pre>';
    var_dump( $split[1], $filename, $fn )
    echo '</pre>';
    
    echo '<hr/>';