如何测试php中是否存在远程图像文件?

Tij*_*Kez 5 php

这会吐出一大堆NO,但图像在那里,路径正确显示<img>.

foreach ($imageNames as $imageName) 
{
    $image = 'http://path/' . $imageName . '.jpg';
    if (file_exists($image)) {
        echo  'YES';
    } else {
        echo 'NO';
    }
    echo '<img src="' . $image . '">';
}
Run Code Online (Sandbox Code Playgroud)

小智 15

file_exists查找本地路径,而不是"http://"URL

使用:

$file = 'http://www.domain.com/somefile.jpg';
$file_headers = @get_headers($file);
if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
    $exists = false;
}
else {
    $exists = true;
}
Run Code Online (Sandbox Code Playgroud)


Ion*_*zău 14

file_exists 使用本地路径,而不是URL.

解决方案是:

$url=getimagesize(your_url);

if(!is_array($url))
{
     // The image doesn't exist
}
else
{
     // The image exists
}
Run Code Online (Sandbox Code Playgroud)

更多看到这个信息.

此外,寻找响应头(使用该get_headers功能)将是一个更好的选择.只需检查响应是否为404:

if(@get_headers($your_url)[0] == 'HTTP/1.1 404 Not Found')
{
     // The image doesn't exist
}
else
{
     // The image exists
}
Run Code Online (Sandbox Code Playgroud)

  • 这非常昂贵.在检索信息之前下载整个图像.您最好只查看请求的标题.查看get_headers().http://php.net/manual/en/function.get-headers.php (3认同)