PHP cURL 以同时保存图像并获得 Header 响应

PHP cURL to Simultaneously Save Image & Get Header Response

我正在尝试使用 cURL 将图像保存到文件的同时 returning header 在加载时 returned保存文件。

原因是因为每次加载图像时都会生成一个唯一的 cookie and/or 保存,所以如果我保存文件然后对同一图像执行另一个请求 URL 获取 cookie,cookie 将不会与保存的图像(它是验证码图像)正确配对。

图像只能加载一次,并且在图像的单次加载中必须保存它(没有re-requesting来自服务器 ) 并同时显示 headers 以便我可以获得在加载和保存图像时生成的 cookie。

这是我目前所掌握的,return header 并且确实保存了文件,但是当以 .jpg 形式查看时文件已损坏。如果我将文件类型更改为 .txt,我可以看到 headers,但是 headers 下面是一堆不是图像的乱码。所以很明显,正在保存的文件是 header 的组合,然后应该是图像,我只是无法单独获取它们,同时确保只有一个图像请求。

function getImageandCookie($ImageURL) {
    $rand = rand();
    $image_file = $_SERVER['DOCUMENT_ROOT'] . '/image/' . $GLOBALS['id'] . $rand . '.jpg';

    $fp = fopen ($image_file, 'w+');

    $ch = curl_init($ImageURL);

    curl_setopt($ch, CURLOPT_FILE, $fp);      
    curl_setopt($ch, CURLOPT_HEADER, 1);    
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);      
    curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36');

    $data = curl_exec($ch);

    curl_close($ch);
    fclose($fp); 
    return $data;
}

更多详情: 我正在尝试将图像保存到我服务器上的一个文件中,同时使 header 编辑 return,同时加载该图像以供我的脚本的其余部分使用。

如果您加载此图像:http://ipv4.google.com/sorry/image?id=2125815723022350864&hl=en 您会看到创建了一个 cookie,该 cookie "tied" 用于图像中的文本。如果您重新加载图像或向同一个 URL 发出新请求,则会创建一个新的 cookie 和图像 "pair"。

所以我需要一次加载该图像并将其保存到文件中,同时抓取 headers(因为那是 "tied" 到该特定图像的 cookie 所在的位置)同时确保只请求一次图像。

2 小时后...

<?
//error_reporting(E_ALL);
//ini_set('display_errors', '1');

    $image_file = "captcha.jpg";
    //$cookie = "gcookie";

    $ch = curl_init("http://ipv4.google.com/sorry/image?id=2125815723022350864&hl=en");  
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    //curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie);
    //curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);      
    curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36');
    $data = curl_exec($ch);
    //split the header and body of request
    $matches = preg_split('/^\s*$/im', $data);
    $header = $matches[0];
    //extract cookie from header
    preg_match_all('/Set-Cookie: (.*?)\s+/i', $header, $gCookie, PREG_PATTERN_ORDER);
    $gCookie = $gCookie[1][0];
    echo $gCookie;
//GOOGLE_ABUSE_EXEMPTION=ID=a85908efa22e6f9b:TM=1429660423:C=c:IP=x.x.x.x-:S=APGng0vbHyNi1KCn9O1bnspO8BgF4LFEhQ;

    //The body is the image, we cleanup the header/body line break and save it
    $body = $matches[1] ;
    $body = implode("\n", array_slice(explode("\n", $body), 1));
    file_put_contents($image_file, $body);

curl_close($ch); 

不难理解,当我们设置CURLOPT_HEADER, 1时,响应头在$data = curl_exec($ch);里面,那么,我们只需要拆分headerbodyheader 中找到 cookie 并将 body(图像)保存到文件。