PHP 检查文件是否存在于 webp 图像上不起作用
PHP checking if file exists on webp image not working
所以我正在尝试检查从 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 版本是 PHP/5.6.30
对于这种情况,您需要使用 CURL,因为它是 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;
}
}
好的,正如 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);
}
感谢 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);
}
所以我正在尝试检查从 get_the_post_thumbnail_url()
不过这并没有像我期望的那样工作。 这是我正在使用的代码:
if (!file_exists($thePostThumbUrl))
$thePostThumbUrl = str_replace("_result.webp", "." . $ext, $thePostThumbUrl);
如果我回显拇指 url 它会得到正确的 .webp 格式图像
echo $thePostThumbUrl . '<br/ >';
显示:
图片url + _result.webp
我知道我使用的 PHP 版本是 PHP/5.6.30
对于这种情况,您需要使用 CURL,因为它是 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;
}
}
好的,正如 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);
}
感谢 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);
}