Category Archives: PHP

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");

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

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

return $response;