Send and Receive JSON POST Requests with PHP

Posted by Methylated on September 19, 2012

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

  $options = Array('http' => Array(
    'method' => "POST",
    'header'=> "Accept-language: enrn".
       "Content-type: application/x-www-form-urlencodedrn",
       "Content-Length: " . strlen($data) . "rn",
    '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;


Use this link to trackback from your own site.


Questions? concerns? corrections? Contact us!