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


How do I test if an remote image file exists in 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 . '">';
}

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

一个解决方案是:

$url=getimagesize(your_url);
if(!is_array($url))
{
     // The image doesn't exist
}
else
{
     // The image exists
}

有关详细信息,请参阅此。

此外,查找响应标头(使用get_headers函数)将是更好的选择。只需检查响应是否为404:

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

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;
}
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if($retcode==200) echo 'YES';
else              echo 'NO';

这就是我所做的。它涵盖了获取标头的更多可能结果,因为如果你不能访问文件,它并不总是"404找不到"。有时是"永久移动"、"禁止"和其他可能的信息。然而,如果该文件存在并且可以访问,那么它只是"200 OK"。使用HTTP的部分可以有1.1或1.0,这就是为什么我只是使用strpos在任何情况下都更可靠。

$file_headers = @get_headers( 'http://example.com/image.jpg' );
$is_the_file_accessable = true;
if( strpos( $file_headers[0], ' 200 OK' ) !== false ){
    $is_the_file_accessable = false;
}
if( $is_the_file_accessable ){
    // THE IMAGE CAN BE ACCESSED.
}
else
{
    // THE IMAGE CANNOT BE ACCESSED.
}
function remote_file_exists($file){
$url=getimagesize($file);
if(is_array($url))
{
 return true;
}
else {
 return false;
}
$file='http://www.site.com/pic.jpg';
echo remote_file_exists($file);  // return true if found and if not found it will return false