【问题标题】:Intermittent HTTP400 (bad request) when using FQL with file_get_contents()将 FQL 与 file_get_contents() 一起使用时出现间歇性 HTTP400(错误请求)
【发布时间】:2012-05-03 16:57:21
【问题描述】:

我的网页使用 PHP 进行 FQL 请求,获取登录用户的好友数,代码如下:

$graph = 'https://graph.facebook.com/fql?q=';
$graph .= 'SELECT+friend_count+FROM+user+WHERE+uid%3Dme%28%29';
$graph .= '&access_token=' . $access_token;
$result = file_get_contents($graph);

大约 80% 的时间可以正常工作,但有时我会收到 400 Bad Request。我注意到这似乎是由将“q”与“access_token”分开的&符号被转义的;即我明白了(不起作用):

https://graph.facebook.com/fql?q=SELECT+friend_count+FROM+user+WHERE+uid%3Dme%28%29&access_token=AAAF8VR3YZCpQBAGiX16jvZAwaEciTwZB1QZAaUjcjy82Ce7Ov7nPqNxjsKM1SAZASGVcZCJ80R9KJZBJYrjKmsDVK6YNrPGA7plPVuwCFZCaOwZDZD

取而代之的是(有效 - 相同的请求,但 '&' 已替换为 '&'):

https://graph.facebook.com/fql?q=SELECT+friend_count+FROM+user+WHERE+uid%3Dme%28%29&access_token=AAAF8VR3YZCpQBAGiX16jvZAwaEciTwZB1QZAaUjcjy82Ce7Ov7nPqNxjsKM1SAZASGVcZCJ80R9KJZBJYrjKmsDVK6YNrPGA7plPVuwCFZCaOwZDZD

我尝试相应地调整我的代码,以便 PHP 明确告诉字符串替换转义的 & 符号,但无济于事:

$graph = 'https://graph.facebook.com/fql?q=';
$graph .= 'SELECT+friend_count+FROM+user+WHERE+uid%3Dme%28%29';
$graph .= '&access_token=' . $access_token;
$result = file_get_contents($graph);
$graphNoEscape = str_replace('&', '&', $graph);
$result = file_get_contents($graphNoEscape);

有人知道问题的解决方法吗?令人讨厌的是,这段代码有时有效,但并非一直有效!

【问题讨论】:

    标签: escaping facebook-php-sdk facebook-fql file-get-contents ampersand


    【解决方案1】:

    对于发现此问题并遇到相同问题的任何人,这就是我解决它的方法:

    首先,我告诉服务器使用 public_html/www 文件夹中的一个 php.ini,PHP 版本 5.3。

    然后我编辑我的代码如下:

    $graph = 'https://graph.facebook.com/fql?q='; 
    $graph .= urlencode('SELECT friend_count FROM user WHERE uid = me()');
    $graph .= '&access_token='.$access_token; 
    $graphNoEscape = str_replace('&', '&', $graph); 
    $file_contents = file_get_contents($graphNoEscape); 
    $fql_result = json_decode($file_contents); 
    $friend_count = mysql_real_escape_string($fql_result->data[0]->friend_count);
    

    诚然,我可能已经用 str_replace() 完成了它,但它仍然有效:)

    希望这可以帮助某人。

    【讨论】:

    • & 仅当您在 URL 中使用 & 字符作为 HTML 属性的一部分时才需要(但也不是绝对需要)。通常,它不应出现在 URL 中。
    猜你喜欢
    • 1970-01-01
    • 2014-10-24
    • 1970-01-01
    • 1970-01-01
    • 2016-09-11
    • 2012-12-14
    • 2020-03-01
    • 2015-07-05
    • 1970-01-01
    相关资源
    最近更新 更多