Twitter不接受PHP的cURL,但是Linux'

时间:2015-12-03 06:43:42

标签: php curl twitter

在尝试使用Twitter的GET statuses/user_timeline API时,我自己编写了一些不错的PHP脚本来生成所有需要的值,但是如果我想执行它,它只是给了我

  

string(0)“”

代码400,这意味着,根据Twitter的API Response Codes

  

请求无效或无法以其他方式提供。随附的错误消息将进一步解释。在API v1.1中,没有身份验证的请求被视为无效,并将产生此响应。

但是这个相同的请求在普通终端curl中工作正常。

以下是我的脚本中的代码段,它生成Linux-Command并执行请求:

$auth_str  = "Authentication: OAuth ...";
$headers = array($auth_str);
// ...

if($method == "POST")
{
    echo "curl --request 'POST' '{$url}' --data '{$fields_string}' --header '{$auth_str}' --verbose";
} else
{
    echo "curl --get '{$url}' --data '{$fields_string}' --header '{$auth_str}' --verbose";
}

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url."?".$fields_string);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER , true);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$content = curl_exec($ch);

2 个答案:

答案 0 :(得分:0)

您应该将GET/POST分成两个不同的部分,类似于命令行示例。

$ch = curl_init();
if($method == "POST"){
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
}
else{
    curl_setopt($ch, CURLOPT_URL, $url."?".$fields_string);
}
// remove CURLOPT_CUSTOMREQUEST

// rest of the curl opts go here!

答案 1 :(得分:0)

我没有让这个特殊的脚本工作,但我找到了TwitterOAuth,这是一个非常有用的PHP库,让我的生活变得如此简单。