PHP實現(xiàn)上傳圖片到 zimg 服務(wù)器
最近我們項目需要一臺圖片服務(wù)器存儲用戶頭像,我們使用 zimg 處理和存儲圖片,下面簡單介紹一下如何使用 PHP 上傳圖片到 zimg,并獲取相應(yīng)圖片的返回信息
使用 curl 庫實現(xiàn)上傳
根據(jù) zimg 使用文檔,我們想要讓 zimg 返回 json 信息,就必須 raw_post 上傳圖片,下面是演示代碼
$upload_url = 'http://192.168.0.99:5000/upload';
$image_file = './test.jpg';
// 獲取圖片后綴
$value = explode(".", $image_file);
$extension = strtolower(array_pop($value));
// 生成本地臨時存儲路徑,并生成相應(yīng)文件夾
$dir = 'aurthur';
$save_path = 'uploads/'.$dir.'/'.date('Y').'/'.date('md').'/';
$save_rule = md5(uniqid(mt_rand(), true));
if(!is_dir($save_path)){
if(false === mkdir($save_path, 0700, true)){
exit('創(chuàng)建文件夾失敗');
}
}
$save_image_file = $save_path.$save_rule.".$extension";
// 把圖片存儲到臨時路徑
file_put_contents($save_image_file, file_get_contents($image_file));
// 獲取臨時保存的圖片的真實地址(絕對路徑)
$realpath = realpath($save_image_file);
// 上傳圖片到 zimg 圖片存儲服務(wù)
$ch = curl_init();
// 將圖片內(nèi)容讀取到變量 $post_data ;
$post_data = file_get_contents($realpath);
$headers = array();
// 一定要添加此 header
$headers[] = 'Content-Type:'.$extension;
curl_setopt($ch, CURLOPT_URL, $upload_url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);// raw_post方式
$info = curl_exec($ch);
curl_close($ch);
$json = json_decode($info, true);
$signature = $json['info']['md5'];
echo $signature;
如果想測試代碼的話,請把上面的uploadurl改成你自己的zimg服務(wù)器地址,并把image_file 改成你需要上傳的圖片的路徑
相關(guān)文章
PHP實現(xiàn)騰訊短網(wǎng)址生成api接口實例
騰訊短網(wǎng)址(url.cn短鏈接)生成api接口是騰訊官方對外公開的短網(wǎng)址生成接口,可以將一個冗長的鏈接縮短成10個字符以內(nèi)的短鏈接,需要的朋友跟隨小編一起看看吧2020-12-12
yii2使用GridView實現(xiàn)數(shù)據(jù)全選及批量刪除按鈕示例
本篇文章主要介紹了yii2使用GridView實現(xiàn)數(shù)據(jù)全選及批量刪除按鈕示例,具有一定的參考價值,有興趣的可以了解一下。2017-03-03
PHP isset empty函數(shù)相關(guān)面試題及解析
這篇文章主要介紹了PHP isset empty函數(shù)相關(guān)面試題及解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-12-12
PHP表單提交后引號前自動加反斜杠的原因及三種辦法關(guān)閉php魔術(shù)引號
一般空間商提供的服務(wù)器空間默認(rèn)PHP 指令 magic_quotes_gpc是on的,也就是打開的。我們通常用stripslashes() 函數(shù)刪除自動添加的反斜杠。2015-09-09
Laravel框架實現(xiàn)調(diào)用百度翻譯API功能示例
這篇文章主要介紹了Laravel框架實現(xiàn)調(diào)用百度翻譯API功能,結(jié)合實例形式分析了基于Laravel框架的百度翻譯API調(diào)用相關(guān)操作技巧,需要的朋友可以參考下2019-05-05

