15

我打算使用其 api 匿名上传图像到 imgur,我在匿名上传类别中注册了我的应用程序并获得了客户端 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);

?>
4

3 回答 3

30

发送client_idpost 变量是问题所在。它需要在请求标头中发送。此外,您正在请求 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

带有调试输出的基于此代码的实时功能示例源代码。

于 2013-06-26T20:43:40.577 回答
8

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

<?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); 

?>
于 2013-06-27T11:58:56.147 回答
5

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

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

于 2014-02-09T09:48:21.410 回答