curl获取远程下载文件--超简单

//获取唯一路径
function createId($length = 20, $prefix = '')
{
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_';
    $id = '';
    for ($i = 0; $i < $length; $i++) {
        $id .= $characters[rand(0, strlen($characters) - 1)];
    }
    return $prefix.$id;
}

//保存
function urlToLocalCurl($url){
    $ext = 'jpg';
    $tmp_path = 'D:\phpstudy_pro\WWW\others\\';
    $tmp_name = createId(10);
    $output = $tmp_path.$tmp_name.'.'.$ext;
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);  //兼容https路径文件(忽略证书)
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);  //兼容https路径文件(忽略证书)
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    $file = curl_exec($ch);
    curl_close($ch);
   // $file = file_get_contents($url); (也可以用此种方法)
    if(file_put_contents($output, $file)) {
        return $output;
    }
    curl_close($ch);
    return false;
}
echo urlToLocalCurl('https://res.shiquaner.zookingsoft.com/6a47e845bf3a6dbfeb3eb8ac798161c5.png');
//输出路径: D:\phpstudy_pro\WWW\others\H1R8XxRK8e.jpg

  

posted @ 2022-03-04 11:14  龙卷风之殇  阅读(628)  评论(0)    收藏  举报