将数据发布到PHP脚本然后处理它

时间:2015-09-01 08:44:32

标签: php curl http-headers http-post httprequest

我试图向我的PHP脚本发出HTTP POST请求。但是,它似乎无法检索请求数据。

为了模拟POST请求,我使用了Request Maker并通过http://php-agkh1995.rhcloud.com/lta.php的网址和var1=65059的请求数据发送。 使用else语句中的默认网址完全正常,但不是其他

我怀疑请求标头是错误的,除非我的代码存在重大缺陷

lta.php

$stopid=$_POST['var1'];
$defurl = ""; // Default url

if(!empty($stopid)){
$defurl = 'http://datamall2.mytransport.sg/ltaodataservice/BusArrival?BusStopID=$stopid';
} else {
 $defurl = 'http://datamall2.mytransport.sg/ltaodataservice/BusArrival?BusStopID=83139';
}   

$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $defurl,
CURLOPT_USERAGENT => 'Ashton',
CURLOPT_HTTPHEADER => array('AccountKey: ********', 'UniqueUserId: ******', 'accept: application/json')
));

$resp = curl_exec($curl);
curl_close($curl);
echo($resp); // To test if data is displayed or not 
return $resp;  

已发送请求标头

POST /lta.php HTTP/1.1
Host: php-agkh1995.rhcloud.com
Accept: */*
Content-Length: 10
Content-Type: application/x-www-form-urlencoded

1 个答案:

答案 0 :(得分:0)

您可以使用array_key_exists来测试POST变量的存在性

if(array_key_exists($_POST,'var1')){
    $stopid=$_POST['var1'];
    $defurl = "http://datamall2.mytransport.sg/ltaodataservice/BusArrival?BusStopID=$stopid";
} else { 
 ..
}

PS:如果您的$defurl默认设置为else案例值,则甚至不需要else子句