php 下载网络图片到本地 遇到httpcode为0的错误

版权声明: https://blog.csdn.net/yangshuolll/article/details/79504346

先上成功用php下载网络图片到本地的代码:

<?php
//Download.php
class Download{
    public static function downloadImage($url, $path='images/')
    {
        $UserAgent = 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; .NET CLR 3.0.04506; .NET CLR 3.5.21022; .NET CLR 1.0.3705; .NET CLR 1.1.4322)';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_USERAGENT, $UserAgent);
        //curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 300);
        $file = curl_exec($ch);
        print curl_error($ch);

        $httpCode = curl_getinfo($ch,CURLINFO_HTTP_CODE);
        echo $httpCode;
        curl_close($ch);

        Download::saveAsImage($url, $file, $path);
    }

    public static function saveAsImage($url, $file, $path)
    {
        $filename = pathinfo($url, PATHINFO_BASENAME);
        $resource = fopen($path . $filename, 'a');
        fwrite($resource, $file);
        fclose($resource);
    }
}

<?php
//pic.php
require_once "Download.php";

Download::downloadImage("https://dm.victoriassecret.com/p/760x1013/tif/da/85/da85d73c28574464ade3dbe6ed6086ec/075_S18_BRA_042_RS_076_e6183099.jpg");




httpCode返回为0的原因是因为之前下载时忽略了在参数中添加了user-agent这个选项,导致下载的服务器认为是爬虫而拒绝了访问的请求,如果添加上了user-agent之后,爬虫模拟浏览器请求事件,就可以把图片下载下来了。



猜你喜欢

转载自blog.csdn.net/yangshuolll/article/details/79504346