在PHP中验证许多图像URL而不下载

时间:2013-07-10 10:28:12

标签: php image url curl amazon-ec2

注意:这是一个性能问题

我在mysql数据库中有20,000个图像网址,我有一个1分钟的间隔cron运行来检查图像网址是否有效且没有损坏。它在EC2上运行很小。我已经尝试过像@GetImageSize这样的方法,检查标题和cURL,但它们最多需要10分钟来完成一项工作。我想知道是否有任何方法不涉及下载图像,并且非常快。

以下是针对某些 25张图片中的以下建议(信用和赞誉)的一些测试

function method2($link){                               //45sec
    if (@GetImageSize($link)) {
        echo  "image exists ";
    } 
}

function method4($url){                            //13 sec
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_NOBODY, 1);
    curl_setopt($ch, CURLOPT_FAILONERROR, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    if(curl_exec($ch)!==FALSE)    {
            echo  "image exists ";
    }
}


function method3($filename){                          //20sec
    $h = fopen($filename, 'r');
    if ($h !== false) {
        echo 'File exists';
            fclose($h);
    }
}

function method5($url){                             //21 sec 
    if(@file_get_contents($url,0,NULL,0,1)){
        echo "image exists";
    }
}

function method6($url){                             //22 sec
    if (false === file_get_contents($url,0,null,0,1)) {
        echo "no ";
    }
}

function method1($url){                                //13 sec
    exec("wget --spider -v ".$url);
}

2 个答案:

答案 0 :(得分:1)

如果主机上的allow_url_fopen为“开启”,那么您可以fopen该网址,只需将其关闭即可,无需阅读任何内容。

$h = fopen('http://www.example.com/img.jpg', 'r');
if ($h !== false) {
    echo 'File exists';
    fclose($h);
else {
    echo 'File does not exist';
}

由于您似乎与目标服务器的所有者保持联系,因此您可能应该采取另一种方法。调用您将在远程服务器上托管的脚本,该脚本返回文件系统中存在的文件列表。然后从你的结尾调用这个脚本。在任何情况下,这都是可取的,因为你每分钟有20k的请求非常难以达到目标。

答案 1 :(得分:0)

你可以使用像“file_exists”这样的php函数。有关更多信息,请点击该链接 http://php.net/manual/en/function.file-exists.php

或使用此

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