Processing HTTP Post with Array

Written by Leif Stenfeldt. Posted in PHP, Programmering

At the client side:
read more…

function do_post_request ($url, $data, $headers = array()) {
// Turn $data into a string
$dataStr = http_build_query($data);
// Turn headers into a string
$headerStr = '';
foreach ($headers as $key => $value) if (!in_array(strtolower($key),array('content-type','content-length'))) $headerStr .= "$key: $value\r\n";
// Set standard headers
$headerStr .= 'Content-Length: '.strlen($data)."\r\nContent-Type: application/x-www-form-urlencoded"
// Create a context
$context = stream_context_create(array('http' => array('method' => 'POST', 'content' => $data, 'header' => $headerStr)));
// Do the request and return the result
return ($result = file_get_contents($url, FALSE, $context)) ? $result : FALSE;
}

$url = 'http://sub.domain.tld/file.ext';
$postData = array(
'send_email' => $_REQUEST['send_email'],
'send_text' => $_REQUEST['send_text']
);
$extraHeaders = array(
'User-Agent' => 'My HTTP Client/1.1'
);

var_dump(do_post_request($url, $postData, $extraHeaders));

At the server side:

print_r($_POST);
/*
Outputs something like:
Array (
[send_email] => Some Value
[send_text] => Some Other Value
)
*/

$message = $_POST['send_text'];
echo $message;
// Outputs something like: Some Other Value

—————————————


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, 'rb', false, $ctx);
 if (!$fp) {
    throw new Exception("Problem with $url, $php_errormsg");
  }
  $response = @stream_get_contents($fp);
  if ($response === false) {
    throw new Exception("Problem reading data from $url, $php_errormsg");
  }
  return $response;
}
Does POST array:

$postdata = array( 
    'send_email' => $_REQUEST['send_email'], 
    'send_text' => $_REQUEST['send_text']);
2484 views

Leave a comment