Search code examples
phpfile-exists

Having troubles with file_exists and is_file


I've prepared this bit of code, and as you can see I've commented out my problem area

//prepare the image file path that includes the isbn in the file name
    $imageFilePath = '"./data/images/' . $book[0] . '.jpg"';

            // Debugging
    // $var = "==>" . file_exists($imageFilePath) . "<==is it true?";
    // $str .= $var;
    // //tests if file is NOT there, if it isn't the imagepath reflects the default image
    // if (file_exists($imageFilePath) == false){

        // $imageFilePath = '"./data/images/default.jpg"';
    // }

My image path variable works like a charm, now I want to use a default image if the file doesn't exist. When the if statement is uncommented all my images become a default image

I've tried is_file and file_exists, to no avail. You can also see that I try to capture the result with the $var variable, there is no space between the ==> and the <==.

I've just started learning programming, and in general I am usually able to debug with an echo here and there or by using the internet. I can't find a solution.

All help is much appreciated, and thanks in advance


Solution

  • You can do something like that

    $imageFilePath = "somethingToCheck";
    $imageFilePathDefault = "somethingDefault";
    $imageFilePath = file_exists($imageFilePath) ? $imageFilePath : $imageFilePathDefault;
    

    For file_exists explaination and argument accepted, please take a look here

    For the third line of code, let's interpret it like:

    if(file_exists($imageFilePath))
     $imageFilePath = $imageFilePath; //confirm that is valid
    else
     $imageFilePath = $imageFilePathDefault; //change to default
    

    Edit after your edit, i suggest also to remove double quotas from your path