PHP下载远程图片到本地的函数代码

寻技术 PHP编程 2024年02月08日 227

本篇文章给大家介绍PHP相关知识,主要内容是教大家怎么使用php下载采集的图片到本地并保存,希望对需要的朋友有所帮助!

PHP下载远程图片到本地的函数代码:

function down_remote_img($url='', $dirName='.', $fileName=''){
    if(empty($url)) return ['code'=>1,'msg'=>'地址不能为空'];
    $header = array(
        'User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:45.0) Gecko/20100101 Firefox/45.0',
        'Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
        'Accept-Encoding: gzip, deflate',);

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($curl, CURLOPT_ENCODING, 'gzip');
    curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
    $file = curl_exec($curl);
    $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    curl_close($curl);

    if ($code == 200) {//把URL格式的图片转成base64_encode格式的!
        $imgBase64Code = "data:image/jpeg;base64," . base64_encode($file);
    }

    $img_content = $imgBase64Code;//图片内容

    //echo $img_content;exit;
    if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $img_content, $result)) {
        $fileType = $result[2];//得到图片类型png?jpg?gif?


        $fileName = $fileName == '' ? time() . rand(0, 9) . '.' . $fileType : $fileName. '.' . $fileType;
        $dirName = $dirName == '' ? './uploads/temp/' . date('Ym', time()) : $dirName;

        if (!file_exists($dirName)) {
            mkdir($dirName, 0777, true);
        }

        $res = @fopen ( $dirName . '/' . $fileName, "a" );
        fwrite($res, $file);
        fclose($res);

        return ['code'=>0,'msg'=>'sucess','path'=>$dirName . '/' . $fileName,'filename'=>$fileName];
    }

    return ['code'=>1,'msg'=>'下载失败'];
}
关闭

用微信“扫一扫”