PHP文件下载

$images = [
    'http://www.thinkphp.cn/Uploads/editor/2017-11-02/59fac47ed670b.png',
    'http://www.thinkphp.cn/Uploads/editor/2017-11-02/59fac48995e58.png'
];

function download($url, $path = 'd:/images/'){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
    $file = curl_exec($ch);
    curl_close($ch);
    $filename = pathinfo($url, PATHINFO_BASENAME);
    $resource = fopen($path . $filename, 'a');
    fwrite($resource, $file);
    fclose($resource);
}

foreach ( $images as $url ) {
    //var_dump($url);exit();
    download($url);
}

封装一个类

class Spider {
 
  public function downloadImage($url, $path = 'd:/images/')
  {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
    $file = curl_exec($ch);
    curl_close($ch);
    $filename = pathinfo($url, PATHINFO_BASENAME);
    $resource = fopen($path . $filename, 'a');
    fwrite($resource, $file);
    fclose($resource);
  }
}  

封装成类之后,我们可以这样调用

$spider = new Spider();
 
foreach ( $images as $url ) {
  $spider->downloadImage($url);
}

 链接为302的情况

$ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//若给定url自动跳转到新的url,有了下面参数可自动获取新url内容:302跳转
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
//设置cURL允许执行的最长秒数。
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0');
        curl_setopt($ch, CURLOPT_REFERER, $url);
        curl_setopt($ch, CURLOPT_ENCODING, 'gzip, deflate');
        $content = curl_exec($ch);
//获取请求返回码,请求成功返回200
        $code = curl_getinfo($ch,CURLINFO_HTTP_CODE);
        $headers = curl_getinfo($ch);
原文地址:https://www.cnblogs.com/pcx105/p/8358357.html