顯示廣告
隱藏 ✕
看板 Knuckles_note
作者 Knuckles (站長 那克斯)
標題 [PHP] 使用 Imgur API 上傳圖片
時間 2015年01月21日 Wed. PM 11:09:55


使用 PHP 搭配圖床空間 Imgur 提供的 API 來上傳圖片

參考 http://api.imgur.com/
若網站或APP是免費的,則 Imgur API 可免費使用

若有營利(放廣告也算),就要依用量來付費
[圖]

如果每天上傳圖片的次數不會超過 1250 次的話也是免費

圖片上傳後,只要一直有人看在的話可以永久保存
若半年沒有任何觀看次數的話就會被刪除

先在 Imgur 註冊一個帳號後,取得 Client ID
[圖]

一開始 Created Apps 是空的,先點「create your own!」

在 Api 的說明文件點「register」
[圖]


輸入 App 名稱,認證方式選「OAuth 2 authorization without a callback URL」
接著輸入 E-mail、Description 後,點「Submit」
[圖]


取得了 Client ID:
[圖]




要使用商業版 API 的話,要到 MashApe 這個整合各種 API 的網站來用
https://market.mashape.com 註冊一個帳號
在 Default Application 新增一個API
[圖]


搜尋 imgur 後點進去
[圖]


在 PRICING 這邊選免費的這個方案即可,之後用量大再改用付費的
[圖]


在 DOCUMENTATION 這邊會列出 API 有哪些功能可以用
選擇 image 的 upload,在 Authorization 輸入「Client-ID XXXXXXXXX」
其中 XXXXXXXXX 為之前在 Imgur 網站取得的 client ID
X-Mashape-Key 選擇 Default Application,將右邊出現的 Mashape Key 記下來
image 可輸入某個圖片的網址
[圖]

按下方的 TEST ENDPOINT 就可以測試 API 傳回的結果正不正確了


在 PHP 寫一個 function imgur_upload()
使用這個 API 上傳圖片

API 網址、Client ID、Mashape Key 這三個參數要用 http header 的方式送出
圖檔、名稱與其他參數要用 post 的方式送出

<?php
function imgur_upload($image, $title='') {
	
$url = 'https://imgur-apiv3.p.mashape.com/3/image/';
	
$mashape_key = "{X-Mashape-Key}"; //填入自己的 Mashape Key
	
$client_id = "{Client ID}"; //填入自己的 Client ID

	
//要用 http header 送出的參數
	
$http_header_array = [
	
	
"X-Mashape-Key: $mashape_key",
	
	
"Authorization: Client-ID $client_id",
	
	
"Content-Type: application/x-www-form-urlencoded",
	
];

	
//要用 post 送出的參數
	
$curl_post_array = [
	
	
'image' => $image,
	
	
'title' => $title,
	
];

	
//將 http header 與 post 加進 curl 的 option
	
$curl_options = [
	
	
	
CURLOPT_HTTPHEADER => $http_header_array,
	
	
	
CURLOPT_POST => true,
	
	
	
CURLOPT_POSTFIELDS => http_build_query($curl_post_array),
	
];
	
$curl_info = null;
	
$curl_result = use_curl_opt($url, $curl_options, $curl_info);

	
return $curl_result;
}

function use_curl_opt($url, $options = [], &$curl_info = null) {
	
$ch = curl_init();
	
$default_options = [
	
	
CURLOPT_URL => $url,
	
	
CURLOPT_HEADER => 0,
	
	
CURLOPT_VERBOSE => 0,
	
	
CURLOPT_RETURNTRANSFER => true,
	
	
CURLOPT_USERAGENT => "Mozilla/5.0 (Windows NT 5.1; rv:10.0.2) Gecko/20100101 Firefox/10.0.2",
	
];
	
curl_setopt_array($ch, $default_options);
	
curl_setopt_array($ch, $options);
	
$curl_result = curl_exec($ch);
	
$curl_info = curl_getinfo($ch);
	
$curl_error = curl_error($ch);
	
curl_close($ch);

	
if($curl_result){ return $curl_result; }
	
else{ return $curl_error; }
}
?>

其中 function imgur_upload()
輸入的 $imgur 可以是圖片的網址
或是圖片的 base64 編碼

輸出為 JSON 字串

上傳成功時會像這樣
{
  "data": {
    "id": "2btFfXc",
    "title": null,
    "description": null,
    "datetime": 1421852928,
    "type": "image/png",
    "animated": false,
    "width": 200,
    "height": 200,
    "size": 29506,
    "views": 0,
    "bandwidth": 0,
    "vote": null,
    "favorite": false,
    "nsfw": null,
    "section": null,
    "account_url": null,
    "deletehash": "GyBny0zeI9l6vzM",
    "name": "",
    "link": "http://i.imgur.com/2btFfXc.png"
  },
  "success": true,
  "status": 200
}

上傳失敗的話會像這樣
{
  "data": {
    "error": "Could not process upload!",
    "request": "/3/image",
    "method": "POST"
  },
  "success": false,
  "status": 500
}

在網頁加上「上傳圖片」的表單
<form action="imgur_upload.php" enctype="multipart/form-data" method="POST">
 選取圖檔: <input type="file" name="fileData" size="35"/><br/>
 <input type="submit" name="submit" value="上傳"/>
</form>

在 imgur_upload.php 接收使用者上傳的圖片
使用 function imgur_upload() 將圖片上傳至 imgur.com
再將產生的 imgur 圖片網址回傳給使用者

<?php
if(isset($_FILES['fileData']){
	
$file = $_FILES['fileData'];
	
if($file['name'] == ''){ die('image error'); }

	
//讀取上傳的檔案並轉為 base64 字串
	
$filepath = $file['tmp_name'];
	
$handle = fopen($filepath, "r");
	
$data = fread($handle, filesize($filepath));
	
$image_base64 = base64_encode($data);

	
//呼叫前面寫的 function imgur_upload
	
$imgur_result = imgur_upload($image_base64,$file['name']);

	
//顯示 imgur 回傳的 JSON 字串
	
echo $imgur_result;
}
?>


如果要一次上傳多個檔案的話,改成
<form action="imgur_upload_multiple.php" enctype="multipart/form-data" method="POST">
 選取圖檔: <input type="file" name="fileData[]" size="35" multiple/><br/>
 <input type="submit" name="submit" value="上傳"/>
</form>

接收上傳檔案的 imgur_upload_multiple.php
<?php
if(isset($_FILES['fileData']){
	
$files = $_FILES['fileData'];
	
$fileNum = count($files['name']);
	
$imgur_result = [];
	
for($i=0; $i<$fileNum; $i++){
	
	
//讀取上傳的檔案並轉為 base64 字串
	
	
$filepath = $files['tmp_name'][$i];
	
	
$handle = fopen($filepath, "r");
	
	
$data = fread($handle, filesize($filepath));
	
	
$image_base64 = base64_encode($data);
	
	
//呼叫前面寫的 function imgur_upload
	
	
$imgur_result[] = imgur_upload($image_base64,$files['name'][$i])."\n";
	
}


	
//合併 imgur 回傳的 JSON 字串
	
echo "[".implode(",",$imgur_result)."]";
}
?>

--
※ 作者: Knuckles 時間: 2015-01-21 23:09:55
※ 編輯: Knuckles 時間: 2017-05-08 18:40:43
※ 看板: KnucklesNote 文章推薦值: 0 目前人氣: 0 累積人氣: 6589 
分享網址: 複製 已複製
1樓 時間: 2016-08-27 23:21:59 (台灣)
  08-27 23:21 TW
請問SSL certificate problem: unable to get local issuer certificate這是什麼意思
不能在localhost使用吧... 我在自己的測試電腦也不能用 要上傳到server才行
r)回覆 e)編輯 d)刪除 M)收藏 ^x)轉錄 同主題: =)首篇 [)上篇 ])下篇