简体   繁体   English

通过php curl发送“ curl -X GET --header”不起作用

[英]Sending “curl -X GET --header” via php curl not working

So i'm trying to use the https://api.thetvdb.com/swagger api via PHP. 所以我正在尝试通过PHP使用https://api.thetvdb.com/swagger api。

I've successfully managed to get a JWT token from the API using the following method: 我已经成功使用以下方法从API获取了JWT令牌:

function tvdb_post ($url, $userinfo) {
    $ch = curl_init($url);
    $payload = json_encode($userinfo);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);
    curl_close($ch);
    $return = json_decode($result, true);

    return $return; 
}

$userinfo = array (
    'username' => 'dstealth',
    'userkey' => '***{redacted}***',
    'apikey' => '***{redacted}***'
);

$token = tvdb_post('https://api.thetvdb.com/login', $userinfo);

I then copy the token and submit it on the API webpage to submit the token. 然后,我复制令牌并将其提交到API网页上以提交令牌。 It gives me a confirmation message. 它给了我一个确认信息。

The problem arises from the next step. 问题出在下一步。 If I do the previous steps ON the API website page, and then do the next step ON the API webpage, it works just fine. 如果我在API网站页面上执行了前面的步骤,然后在API网站页面上进行了下一步,则可以正常工作。 But when I try to convert the next step into PHP, it gives me a "Not Authorized" messaged. 但是,当我尝试将下一步转换为PHP时,会显示一条消息“未授权”。

The next step on the API webpage is: API网页的下一步是:

curl -X GET --header 'Accept: application/json' --header 'Authorization: Bearer <token>' 'https://api.thetvdb.com/refresh_token'
// returns a response code 200 and refreshes the token successfully.

in php my next step looks like this: 在PHP中,我的下一步看起来像这样:

$authorization = "Authorization: Bearer ***{redacted}*** ";

function tvdb_api ($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', $authorization));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $json = curl_exec($ch);
    curl_close($ch);
    $array = json_decode($json, true);

    return $array;
}

$refresh = tvdb_api('https://api.thetvdb.com/refresh_token');
// This returns a "Not Authorized" error.

Can anyone please tell me what i'm doing wrong between converting the next step from the API webpage to php? 谁能告诉我在将下一步从API网页转换为php之间我做错了什么?

The $authorization variable was outside the function and the function was trying to use it's values. $ authorization变量在函数外部,并且该函数正在尝试使用其值。 Once I moved it inside the function the function worked as expected. 一旦将其移入函数中,该函数将按预期工作。 Sorry for posting! 对不起,发贴!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM