Xampp php 使用 imgur api 尝试 post 图片时权限被拒绝?

Xampp php permission denied when trying to post images using imgur api?

我得到的错误:

Warning: file_get_contents(https://api.imgur.com/3/image): failed to open stream: HTTP request failed! HTTP/1.1 403 Permission Denied in C:\xampp\htdocs\sn0\classes\Image.php on line 22

Notice: Trying to get property of non-object in C:\xampp\htdocs\sn0\classes\Image.php on line 25

Notice: Trying to get property of non-object in C:\xampp\htdocs\sn0\classes\Image.php on line 25

这是我的 Image.php 文件:

<?php
class Image {

        public static function uploadImage($formname, $query, $params) {
                $image = base64_encode(file_get_contents($_FILES[$formname]['tmp_name']));

                $options = array('http'=>array(
                        'method'=>"POST",
                        'header'=>"Authorization: Bearer ###\n".
                        "Content-Type: application/x-www-form-urlencoded",
                        'content'=>$image
                ));

                $context = stream_context_create($options);

                $imgurURL = "https://api.imgur.com/3/image";

                if ($_FILES[$formname]['size'] > 10240000) {
                        die('Image too big, must be 10MB or less!');
                }

                $response = file_get_contents($imgurURL, false, $context);
                $response = json_decode($response);

                $preparams = array($formname=>$response->data->link);

                $params = $preparams + $params;

                DB::query($query, $params);

        }

}
?>

你提出了错误的要求。

开始时您需要生成您的客户端 ID(更多信息@https://api.imgur.com/#registerapp

要执行此操作,请转至 https://api.imgur.com/oauth2/addclient 和 Select 没有用户授权选项的匿名使用 作为授权类型。

使用授权:Client-ID 不是 Bearer,您可以保留 file_get_contents(所以 - 那么您只需要更改授权 header)但是CURL 对此会更好。

CURL 示例:

<?php
class Image
{
    public static function uploadImage($formname, $query, $params)
    {
        $client_id = 'YOUR CLIENT ID';
        $image = base64_encode(file_get_contents($_FILES[$formname]['tmp_name']));
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://api.imgur.com/3/image.json',
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTPHEADER => array(
                'Authorization: Client-ID ' . $client_id
            ) ,
            CURLOPT_POST => TRUE,
            CURLOPT_RETURNTRANSFER => TRUE,
            CURLOPT_POSTFIELDS => array(
                'image' => $image
            )
        ));
        $out = curl_exec($curl);
        curl_close($curl);
        $response = json_decode($out);
        $preparams = array(
            $formname => $response->data->link
        );
        $params = $preparams + $params;
        DB::query($query, $params);
    }
}

file_get_contents() 用于 GET 请求。您需要在 PHP 中使用 CURL 才能从一个服务器向另一个服务器发出 POST 请求。