Send and Receive POST Requests with PHP

This can be used to build an API or generally have different sites and scripts communicate externally.



function postback($url, $params, $optional_headers=null, $decode=true) {
$params['handshake'] = HANDSHAKE;
 $params['url'] = $url;
 $params['remote_ip'] = $_SERVER['REMOTE_ADDR'];
 $data = http_build_query($params);

$options = Array('http' => Array(
 'method' => "POST",
 'header'=> "Accept-language: en\r\n".
 "Content-type: application/x-www-form-urlencoded\r\n",
 "Content-Length: " . strlen($data) . "\r\n",
 'content' => $data));

if ($optional_headers !== null) {
 $params['http']['header'] .= $optional_headers;
 }

$ctx = stream_context_create($options);
$fp = fopen($url, 'r', false, $ctx);
 if (!$fp) throw new Exception("Problem with URL '$url' {$php_errormsg}");

$response = stream_get_contents($fp);
 if ($response === false) throw new Exception("Problem reading data from $url, $php_errormsg");

//var_dump($response);
 if ($decode) $response = json_decode(rawurldecode($response), TRUE);

// Invalid query?
 if (!isset($response['handshake']) || ($response['handshake'] !== HANDSHAKE))
 return NULL;

return $response;
}

 

One thought on “Send and Receive POST Requests with PHP”

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>