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

先上成功用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之后,爬虫模拟浏览器请求事件,就可以把图片下载下来了。



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值