试图用PHP下载远程图像

时间:2016-10-15 14:09:24

标签: php

我试图下载远程图像(来自多个网站),但这些代码都有效

allow_url_fopen已打开,但这些代码将返回0字节

$url = 'http://example.com/image.php';
$img = 'teste.jpg';
file_put_contents($img, file_get_contents($url));

copy('http://example.com/image.php', 'teste.jpg');

当我使用curl(在主机上启用)时,会出现此错误:

错误:无法加载请求的资源。 libcurl返回错误:来自服务器的空回复

curl code:

$ch = curl_init('http://example.com/image.php');
$fp = fopen('teste,jpg, 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);

编辑:尝试以下卷曲选择:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)');
curl_setopt($ch, CURLOPT_FILE, $lfile);

网站由000webhost托管,在用不同的代码尝试了一整天后,我不得不使用代理来访问我的网站,因为它阻止了我

编辑2:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"h.mhcdn.net/store/manga/10738/thumb_cover.jpg?v=1476422230");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)');
//die("here1");
$data = curl_exec($ch);
die("here2");
file_put_contents("test.jpg", $data);
die("here3");
//curl_setopt($ch, CURLOPT_FILE, "test.jpg");

尝试上面的代码,但它不会达到“die(”here2“);”(页面不会加载)只有骰子(“here1”);

编辑3:

$url = "http://h.mhcdn.net/store/manga/10738/thumb_cover.jpg?v=1476422230";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)');
        //die("here1");
        $data = curl_exec($ch);
        file_put_contents("local_file.jpg", $data);
        die("here2");

无法到达here2,只有here1

编辑4:这就是问题:端口80在000web上被阻止了传出连接:https://www.habschned.com/000webhost-com-blocking-port-80-for-outbound-traffic-no-more-curl/

1 个答案:

答案 0 :(得分:0)

我想这很明显,但您是否尝试在浏览器中打开该网址?你能看到这张照片吗?

如果上述答案为YES(最有可能),则远程方很可能阻止脚本获取资源。解决方案是使用cURL尽可能地模拟常规浏览器在HTTP标头方面的行为。

我会从最明显的CURLOPT_USERAGENT和CURLOPT_USERAGENT开始,将它们设置为他们期望的值,你应该没问题。更复杂的访问控制涉及cookie和会话,这更复杂,因为您必须获取引用页面,存储cookie,并在获取资源时发送它。

<强>更新

虽然上述情况属实,但这不是提问者所遇到的问题,这个简单的脚本应该按原样运作:

$url = "http://h.mhcdn.net/store/manga/10738/thumb_cover.jpg?v=1476422230";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)');
$data = curl_exec($ch);
file_put_contents("local_file.jpg", $data);
相关问题