PHP:使用cURL模拟XHR

时间:2011-05-12 01:36:07

标签: php curl xmlhttprequest

今天我正在努力为一些论坛登录做一个cron工作来检查在线统计数据。 login.php脚本接受带有表单提交值的ajax请求:user,password,server和hash id(在隐藏字段中)。我已经可以将值提交到登录脚本并使用cookie jar保留会话但是当我尝试传递所需的参数(来自sendlogin.php)时,它似乎拒绝了没有正确请求标头的请求。所以我需要知道如何使用cURL模拟这个:

GET login.php?user=foo&password=bar&server=1&id=7131c359e534e3790eaefa495d621b2a HTTP/1.1

Host: someloginserver.com
User-Agent: Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1
Accept: application/json, text/javascript, */*; q=0.01
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip, deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
X-Requested-With: XMLHttpRequest
Referer: http://someloginserver.com/sendlogin.php
Cookie: __cfduid=de2fe207593d1135fc2426fb06e3270741303115848; hellobar_current=1300711502; hellobar_1300711502_variation=11462; PHPSESSID=cc621c6f57c43130d51d3147e319d8c2
希望你能帮助我。

2 个答案:

答案 0 :(得分:10)

在PHP api to curl中你可以使用:

curl_setopt($curl, CURLOPT_HTTPHEADER, array(
    "Host" => "someloginserver.com",
    "User-Agent" => "Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1",
    "Accept" => "application/json, text/javascript, */*; q=0.01",
    "Accept-Language" => "en-us,en;q=0.5",
    "Accept-Encoding" => "gzip, deflate",
    "Accept-Charset" => "ISO-8859-1,utf-8;q=0.7,*;q=0.7",
    "Keep-Alive" => "115",
    "Connection" => "keep-alive",
    "X-Requested-With" => "XMLHttpRequest",
    "Referer" => "http://someloginserver.com/sendlogin.php"
));

但是你的实际问题可能是Cookie:我已将其排除在上面。使用COOKIEJAR设置您的cURL请求。制作一个虚假请求以获取当前会话值,然后仅发送您的实际XHR请求。

答案 1 :(得分:10)

该数组格式不起作用。 Curl不接受关联数组。每个元素必须是以下格式的字符串:

    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        "Host: www.somehost.com",
        "User-Agent: Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1",
        "Accept: application/json, text/javascript, */*; q=0.01",
        "Accept-Language: en-us,en;q=0.5",
        "Accept-Encoding: gzip, deflate",
        "Connection: keep-alive",
        "X-Requested-With: XMLHttpRequest",
        "Referer: http://www.somehost.com/"
    ));