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'];
  //print_r($params);
  $data = http_build_query($params);
  //var_dump($data);

  $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);
  //die($url);
  $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;
}