Search code examples
phpfunctionwebp

PHP checking if file exists on webp image not working


So i'm trying to check if there is a webp image format on the url retrieved from get_the_post_thumbnail_url()

This is not working how I would expect though. Here is the code im working with:

if (!file_exists($thePostThumbUrl))
    $thePostThumbUrl = str_replace("_result.webp", "." . $ext, $thePostThumbUrl);

if I echo the thumb url it gets the correct image with a .webp format

echo $thePostThumbUrl . '<br/ >';

Displays:

image url + _result.webp

I know the version of PHP im working with is PHP/5.6.30


Solution

  • Ok so as Akintunde suggested, the file_exists function wont work with the url of the image. So the code needed to be modified to use the server path instead.

    This code does the trick:

    $ext = pathinfo($thePostThumbUrl, PATHINFO_EXTENSION);
    $thePostThumbPath = str_replace("http://localhost", "", $thePostThumbUrl);
    if (!file_exists($_SERVER['DOCUMENT_ROOT'] . $thePostThumbPath)) {
        $thePostThumbUrl = str_replace("_result.webp", "." . $ext, $thePostThumbUrl);
    }
    

    Thansk Akintunde for pointing me in the right direction :)