php curl的ajax请求

时间:2014-05-06 10:09:46

标签: php ajax curl

我有0卷曲的经验,我想运行一个请求,它将在php中返回一个json主体。

使用firefox firbug我可以复制curl顺序,它看起来像这样

curl 'http://*****.com/index.php/home/search/keyword/c815f2fec5?value=keyworkd' -H 
'Host: *****.com' -H 
'User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0' -H
'Accept: */*' -H 
'Accept-Language: en-US,en;q=0.5' -H 
'Accept-Encoding: gzip, deflate' -H
'X-Requested-With: XMLHttpRequest' -H 
'Referer: http://****.com/' -H
'Cookie: _ga=GA1.2.373422434.1399222050; PHPSESSID=l8sf036kjaijt6cjvcqnu992l4'

我可以用php模拟这样的请求吗?

1 个答案:

答案 0 :(得分:1)

当然,根据您的有限信息,不需要做太多不必要的事情:

<?php
    $c = curl_init('http://*****.com/index.php/home/search/keyword/c815f2fec5?value=keyworkd');                 
    curl_setopt($c, CURLOPT_USERAGENT, "User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0");
    curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);         
    curl_setopt($c, CURLOPT_FOLLOWLOCATION, 1);     
    curl_setopt($c, CURLOPT_COOKIE, 
    '_ga=GA1.2.373422434.1399222050; PHPSESSID=l8sf036kjaijt6cjvcqnu992l4');
    curl_setopt($c, CURLOPT_REFERER, 'http://****.com/');
    $z = curl_getinfo($c);
    $s = curl_exec($c);
    curl_close($c);  
?>

编辑:该死的虽然是POST而不是COOKIE,修好了。 Edit2:使用Cookie文件。

<?php
    $cookie_file = "cookie.txt"; //remember to check if it exists
    $c = curl_init('http://*****.com/index.php/home/search/keyword/c815f2fec5?value=keyworkd');                 
    curl_setopt($c, CURLOPT_USERAGENT, "User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0");
    curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);         
    curl_setopt($c, CURLOPT_FOLLOWLOCATION, 1);     
    curl_setopt($c, CURLOPT_COOKIEJAR, $cookie_file);
    curl_setopt($c, CURLOPT_COOKIEFILE, $cookie_file);
    curl_setopt($c, CURLOPT_REFERER, 'http://****.com/');
    $z = curl_getinfo($c);
    $s = curl_exec($c);
    curl_close($c);  
?>