-1
$ch = curl_init();
$fp = fopen("$localName",'w');

curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_URL, $src);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
curl_setopt($ch, CURLOPT_TIMEOUT, 200);
curl_setopt($ch, CURLOPT_AUTOREFERER, false);
curl_setopt($ch, CURLOPT_REFERER, "http://google.com");
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_HEADER, 0);
$rawdata=curl_exec ($ch);
curl_close ($ch);

fwrite($fp, $rawdata); 
fclose($fp);

... 写入文件但无效(0 字节)。请告诉我我做错了什么。

4

4 回答 4

1

我运行了您的代码,但出现了一些错误。我在这里纠正了那些:

$src = '<URL to the image>';
$ch = curl_init($src);

//curl_setopt($ch, CURLOPT_FILE, $fp); This option is not required
//curl_setopt($ch, CURLOPT_URL, $host); Since you are setting the source in init skip this
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
curl_setopt($ch, CURLOPT_TIMEOUT, 200);
curl_setopt($ch, CURLOPT_AUTOREFERER, false);
curl_setopt($ch, CURLOPT_REFERER, "http://google.com");
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE); // Follows redirect responses.

$raw=curl_exec($ch);
if ($raw === false) {
    trigger_error(curl_error($ch));
}

curl_close ($ch);
$localName = basename($src); // The file name of the source can be used locally       
if(file_exists($localName)){    
    unlink($localName);
}

$fp = fopen($localName,'wb');
fwrite($fp, $raw);
fclose($fp);
于 2012-11-19T09:38:10.127 回答
1

原来问题是加载了一些图像,但是 302 重定向状态消息混淆了 curl。

于 2012-11-28T07:46:39.507 回答
0

尝试为图像类型添加 header()。

例如,如果它是 PNG 图像,请在代码中添加:

// ...
header('Content-type: image/png');
file_put_contents($raw);
于 2012-11-19T09:25:07.460 回答
0

玩了一场,您似乎只需要以下内容:

<?
$src = 'http://bit.ly/TT5N5M';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $src);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$output = curl_exec($ch);
curl_close($ch);

$fp = fopen("img.jpg",'w');
fwrite($fp, $output);
fclose($fp);
于 2012-11-19T09:29:27.107 回答