【问题标题】:PHP - Send post data to URL and get the responsePHP - 将帖子数据发送到 URL 并获取响应
【发布时间】:2013-12-31 13:38:46
【问题描述】:

我很难将 POST 数据发送到 twitch api (https://api.twitch.com/kraken/oauth2/token) 并取回 json 代码...这是我当前的代码:

$this->config->load("config", true);
$url = "https://api.twitch.tv/kraken/oauth2/token";
$postvars = "client_id=" . $this->config->item('twitch_clientid', 'config') . "&client_secret=" . $this->config->item('twitch_secret', 'config') . "&grant_type=user_read&redirect_uri=" . $this->config->item('twitch_redirect', 'config') . "&code=" . $key;

$temp = curl_init($url);
curl_setopt($temp, CURLOPT_POST, 1);
curl_setopt($temp, CURLOPT_POSTFIELDS, $postvars);
curl_setopt($temp, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($temp, CURLOPT_HEADER, 0);
curl_setopt($temp, CURLOPT_RETURNTRANSFER, 1);
$result = json_decode(@file_get_contents(curl_exec($temp)), true);

但是...显然我不应该这样做。第一次使用 curl。
错误:

A PHP Error was encountered 
Severity: Warning
Message: file_get_contents(): Filename cannot be empty
Filename: controllers/user.php
Line Number: 37

预期结果:

{
  "access_token": "[user access token]",
  "scope":[array of requested scopes]
}

【问题讨论】:

  • 您遇到什么错误?期望的和实际的结果是什么?

标签: php codeigniter curl twitch


【解决方案1】:

错误在这一行:

$result = json_decode(@file_get_contents(curl_exec($temp)), true);

curl_exec 在 returntransfer 开启时返回 false 或数据 (http://pl1.php.net/curl_exec) 因此代码应该看起来更像

if (! $data = curl_exec($ch)) { 
    //ERROR 
} else {
    $result = json_decode($data, true);
}
curl_close($ch); 

您始终可以将选项 VERBOSE 设置为 true,以便更好地查看发送到服务器的内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-20
    • 2010-11-02
    • 1970-01-01
    • 2011-02-19
    相关资源
    最近更新 更多