天天看點

微信頭像下載下傳到本地伺服器

function download_remote_pic($url) 
    {
        $header = [
            '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);
        $data = 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($data);
        }
        $img_content = $imgBase64Code; //圖檔内容  
        //echo $img_content;exit;  
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $img_content, $result)) {
        	var_dump($result);
            $type = $result[2]; //得到圖檔類型png?jpg?gif?   
            $new_file = "./" . time() . rand(1, 10000) . ".{$type}";
            if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $img_content)))) {
                return $new_file;
            }
        }
    }

$new_file = download_remote_pic('http://thirdwx.qlogo.cn/mmopen/vi_32/nwANWf8RyKblcibnCiauRzcCsD9j3vhmdfeftwXPfvGicXRJE8jFYCxhkiaVaPnWVC2kyFUgtJiaus0paaucMUlkRWg/132');

echo $new_file;