php使用curl保存远程图片jpg|png|jpeg

1413

/**

 * 保持远程图片

 * @param $thumb

 */

function curl_thumb($thumb,$nourl,$default=null){
    if (strpos($thumb,$nourl) === false){
        return $thumb;
    } else {
        //获取文件原文件名
        $defaultname = basename($thumb);
        //获取文件类型
        $suffix = substr(strrchr($thumb, '.'), 1);
        if (!in_array($suffix, array('jpg','gif','png'))) {
            return config('filesystem.disks.common.url').'/img/uimg.png';
        }
        //默认图片
        if ($default != null && $default == $defaultname){
            return config('filesystem.disks.common.url').'/img/uimg.png';
        }
        //设置保存后的文件名
        $savename = md5(time().mt_rand(1000,9999)).'.'.$suffix;
        // 获取远程文件资源
        $ch = curl_init();
        $timeout = 120;
        curl_setopt($ch, CURLOPT_URL, $thumb);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        $file = curl_exec($ch);
        curl_close($ch);
        //$file = file_get_contents($thumb);
        // 设置文件保存路径
        $filedir = '/uavatar/'.str_time();
        $dirName = config('filesystem.disks.public.root').$filedir;
        if (!file_exists($dirName)) {
            mkdir($dirName, 0777, true);
        }
        if ($file){
            // 保存文件
            $res = fopen($dirName.'/'.$savename, 'a');
            fwrite($res, $file);
            fclose($res);
            return config('filesystem.disks.public.url').$filedir.'/'.$savename;
        } else {
            return false;
        }
    }
}