I am writing a script to be executed by a client which will generate an array of floats (which I understand in PHP are supposed to be the same as doubles) and perform a post request to a page which will take the data and compute the mean, returning that data in the response. My plan is to attach send the array in the message body in json format. I found a tutorial online for doing POST
requests in PHP from which I have taken the function do_post_request()
and I can't get around the following exception:
PHP Fatal error: Uncaught exception 'Exception' with message 'Problem with http://localhost/average.php' in /home/yak/restclient.php:20
Stack trace:
#0 /home/yak/restclient.php(5): do_post_request('http://localhos...', '[1.5,1.5,1.5,1....', 'Content-Type=ap...')
#1 {main}
thrown in /home/yak/restclient.php on line 20
The client code:
<?php
$array = array_fill(0,5,1.5);
$data = json_encode($array);
echo $data;
$response = do_post_request("http://localhost/average.php",$data,"Content-Type=application/json");
echo $response;
function do_post_request($url, $data, $optional_headers = null)
{
$params = array('http' => array(
'method' => 'POST',
'content' => $data
));
if ($optional_headers !== null) {
$params['http']['header'] = $optional_headers;
}
$ctx = stream_context_create($params);
$fp = @fopen($url, 'r', false, $ctx);
if (!$fp) {
throw new Exception("Problem with $url");
}
$response = @stream_get_contents($fp);
if ($response === false) {
throw new Exception("Problem reading data from $url);
}
return $response;
}
?>
Would anybody be able to shed some light on this error, or better yet, suggest a better way of doing what I'm trying to do here? I have also tried using the http_post_data()
function, but even after trying some fixes found on SO, I have been unable to get it to work (PHP sees it as an undefined function).
This is the server code:
<?php
header("Content-Type:application/json");
if(!empty($_POST['data'])) {
#calculate mean of each array and send results
$data = $_POST['data'];
$array = json_decode($data);
$mean = array_sum($array)/count($array);
respond(200,"OK",$mean);
} else {
#invalid request
respond(400,"Invalid Request",NULL);
}
function respond($status,$message,$data) {
header("HTTP/1.1 $status $message");
$response['status']=$status;
$response['message']=$message;
$response['data']=$data;
$json_response=json_encode($response);
echo $json_response;
}
?>
This will eventually be adapted to deal with several arrays sent in one message, but to get started I thought this would be quite simple - I was wrong.
UPDATE: Using Arpita's answer the request is now going through but the response indicates an invalid request, as if it is not actually doing a POST.