PHP检查WebP映像上是否存在文件不起作用



所以我试图检查从 get_the_post_thumbnail_url()

检索的URL上是否有WebP映像格式

这不行,但是我的期望如何。这是即时操作的代码:

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

如果我呼应了拇指URL,它将使用.webp格式获得正确的图像

echo $thePostThumbUrl . '<br/ >';

显示:

图像URL _result.webp

我知道PHP IM的版本是PHP/5.6.30

正如Akintunde所建议的那样,file_exists函数无法与图像的URL一起使用。因此,需要修改代码以使用服务器路径。

此代码可以解决:

$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指向我指向正确的方向:)

我编写了一个功能,该功能检查服务器上是否以WebP格式存在给定图像:

function webpExists($img_src){
  $env = array("YOUR_LOCAL_ENV", "YOUR_STAGING_ENV", "YOUR_PROD_ENV");
  $img_src_webp = str_replace(array(".jpeg", ".png", ".jpg"), ".webp", $img_src);
  $img_path = str_replace($env, "", $img_src_webp);
  return file_exists($_SERVER['DOCUMENT_ROOT'] . $img_path);
}

您需要在这种情况下使用卷曲,因为它是一个URL。

示例:

function checkRemoteFile($url)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$url);
    // don't download content
    curl_setopt($ch, CURLOPT_NOBODY, 1);
    curl_setopt($ch, CURLOPT_FAILONERROR, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    if(curl_exec($ch)!==FALSE)
    {
        return true;
    }
    else
    {
        return false;
    }
}

最新更新