php检查外部doman上是否存在文件(从子域访问)

时间:2013-08-18 17:22:24

标签: php curl get-headers

我在http://www.reelfilmlocations.co.uk

上有一个网站

上述网站有一个管理区域,用于上传图像,并在上传/图像目录的子文件夹中创建不同大小的副本。

我正在为移动设备创建一个站点,该站点将在子域上运行,但是使用来自主域的数据库和图像, http://2012.reelfilmlocations.co.uk

我希望能够访问父域中的图像,我可以通过链接到具有完整域的图像来完成,即http:www.reelfilmlocations.co.uk/images/minidisplay/myimage.jpg

虽然我需要先检查图像是否存在...

我有一个php函数,用于检查图像是否存在,如果存在,则返回图像的完整URL。

如果它不存在,我想返回占位符图像的路径。

我有以下功能,如果它存在,则返回正确的图像,但如果它不存在,则只返回占位符图像所在目录的路径,即http://www.reelfilmlocations.co.uk/images/thumbs/。没有no-image.jpg位。

相关网页是:http://2012.reelfilmlocations.co.uk/browse-unitbases/ 我在我的页面上获取图像的代码是:

<img src="<?php checkImageExists('/uploads/images/thumbs/', $row_rs_locations['image_ubs']);?>">

我的php功能:

if(!function_exists("checkImageExists")){
    function checkImageExists($path, $file){
        $imageName = "http://www.reelfilmlocations.co.uk".$path.$file;
        $header_response = get_headers($imageName, 1);
        if(strpos($header_response[0], "404" ) !== false ){
            // NO FILE EXISTS
            $imageName = "http://www.reelfilmlocations.co.uk".$path."no-image.jpg"; 
        }else{
            // FILE EXISTS!!
            $imageName = "http://www.reelfilmlocations.co.uk".$path.$file;
        }
        echo($imageName);   
    }
}

没有让这个工作我做了一些挖掘并阅读有关卷曲的一些帖子:

每次只返回占位符图片。

if(!function_exists("remoteFileExists")){
    function remoteFileExists($url) {
        $curl = curl_init($url);

        //don't fetch the actual page, you only want to check the connection is ok
        curl_setopt($curl, CURLOPT_NOBODY, true);

        //do request
        $result = curl_exec($curl);

        $ret = false;

        //if request did not fail
        if ($result !== false) {
            //if request was ok, check response code
            $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);  
            if ($statusCode == 200 ) {
                $ret = true;   
            }
        }
        curl_close($curl);

        return $ret;
    }
}

if(!function_exists("checkImageExists")){
    function checkImageExists($path, $file){
        $imageName = "http://www.reelfilmlocations.co.uk".$path.$file;

        $exists = remoteFileExists($imageName);
        if ($exists){
            // file exists do nothing we already have the correct $imageName
        } else {
                    // file does not exist so set our image to the placeholder
            $imageName = "http://www.reelfilmlocations.co.uk".$path."no-image.jpg";   
        }
            echo($imageName);
    }
}

我不知道是否可以与获得403,或如何检查是否是这种情况。

我可以尝试的任何指针或事物都会非常感激。

1 个答案:

答案 0 :(得分:1)

我使用CURL,发出HEAD请求并检查响应代码。

未经测试,但应该做到这一点:

 $URL = 'sub.domain.com/image.jpg';
 $res = `curl  -s -o /dev/null -IL -w "%{http_code}" http://$URL`;
 if ($res == '200')
     echo 'Image exists';

上面的代码将使用请购单的状态代码填充$res(请注意我不要将http://前缀包含在$URL变量中,因为我在命令行。

当然可以使用PHP的CURL函数获得相同的效果,上述调用可能无法在您的服务器上运行。如果我有同样的需要,我只是在解释我正在做的事情。