I am new to cURL and I am setting up a test environment to send a cURL POST request using PHP and then I need to mimic the server (responding) program (PHP also) with a status code and payload. After looking and reading up on cURL and corresponding documentation and pertinent RFC documents there are a lot of examples on the request side but I could find no pertinent examples for the response side. My request code is as follows:
$url = 'http://localhost/curlresponder.php';
$fields = array(
'City' => urlencode('Hokeywaka'),
'State' => urlencode('IL'),
'Zip' => urlencode('60677'),
);
foreach($fields as $key => $value)
{$fields_string .= $key . "=" . $value . '&';}
rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
curl_close($ch);
if ($result === FALSE)
{echo 'Return failure ' . '<br />';
else
{Process $result;}
Now I need to know what the responding program code is - assuming the request is received and processed successfully the response code of 200 is to be sent back with a payload attached (which I gather is also POST since the request was POST.
You just need the remote page to post back a JSON script. And by Post back I just mean echo a JSON string on the page. You can use that in your $result var. You might want to create an API access key just to make sure nobody else uses it if you think there might be a security issue.
$result = curl_exec($ch);
$result = json_decode($result,true);
if ($result['status']=="ok"){
echo "Good request";
}else{
echo "Bad request";
}
you can use the function curl_getinfo to obtain the info you wanted,and code like this
<?php
// Create a cURL handle
$ch = curl_init('http://www.stackoverflow.com/');
// Execute
curl_exec($ch);
// Check HTTP status code
if (!curl_errno($ch)) {
switch ($http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE)) {
case 200: # OK
break;
default:
echo 'Unexpected HTTP code: ', $http_code, "\n";
}
}
// Close handle
curl_close($ch);
?>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.