使用imgur api v3使用php匿名上传图像

时间:2013-06-24 06:44:39

标签: php api imgur

我打算使用它的api匿名上传图片,我在匿名上传类别中注册我的应用程序,并获得客户端ID和客户端密码,如何使用php上传图片imgur并检索图像的直接URL? 任何人都可以建议任何例子的链接? 这是我试图做的但我得到错误“致命错误:超过30秒的最大执行时间”

<?php

$client_id = :client_id; //put your api key here
$filename = "images/q401x74ua3402.jpg";
$handle = fopen($filename, "r");
$data = fread($handle, filesize($filename));

//$data is file data
$pvars   = array('image' => base64_encode($data), 'key' => $client_id);
$timeout = 30;
$curl    = curl_init();

curl_setopt($curl, CURLOPT_URL, 'https://api.imgur.com/3/upload.json');
curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $pvars);
$xml = curl_exec($curl);
$xmlsimple = new SimpleXMLElement($xml);
echo '<img height="180" src="';
echo $xmlsimple->links->original;
echo '">';

curl_close ($curl);

?>

3 个答案:

答案 0 :(得分:27)

在post变量中发送client_id是个问题。它需要在请求标头中发送。此外,您正在请求JSON响应,但尝试将其解析为XML。

<?php

$client_id = "FILLMEIN";
$image = file_get_contents("img/cool.jpg");

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.imgur.com/3/image.json');
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Client-ID ' . $client_id));
curl_setopt($ch, CURLOPT_POSTFIELDS, array('image' => base64_encode($image)));

$reply = curl_exec($ch);
curl_close($ch);

$reply = json_decode($reply);
printf('<img height="180" src="%s" >', $reply->data->link);

更新1

Live functional example and source基于此代码并带有调试输出。

答案 1 :(得分:7)

发现错误,我需要将授权详细信息作为标题发送, 例如代码

<?php
$client_id = 'xxxxxxxx';

$file = file_get_contents("test-image.png");

$url = 'https://api.imgur.com/3/image.json';
$headers = array("Authorization: Client-ID $client_id");
$pvars  = array('image' => base64_encode($file));

$curl = curl_init();

curl_setopt_array($curl, array(
   CURLOPT_URL=> $url,
   CURLOPT_TIMEOUT => 30,
   CURLOPT_POST => 1,
   CURLOPT_RETURNTRANSFER => 1,
   CURLOPT_HTTPHEADER => $headers,
   CURLOPT_POSTFIELDS => $pvars
));

$json_returned = curl_exec($curl); // blank response
echo "Result: " . $json_returned ;

curl_close ($curl); 

?>

答案 2 :(得分:5)

如果您对上述脚本有疑问,请尝试使用curl跳过已验证的SSL,如下所示:

curl_setopt($ ch,CURLOPT_SSL_VERIFYPEER,false);