0
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']);

How can I get individual array element to individual PHP var?

Part of a page of POST data processor:

...
$message = $_REQUEST['postdata']['send_text'];
...

What's Wrong?

3
  • Can you try and clarify exactly what the problem is that you are having? Are you getting any error messages? Or is the problem related to the script at the other side, the page you are sending data to? Commented Oct 19, 2011 at 15:03
  • POST data processor shows nothing, it's receives nothing. Commented Oct 19, 2011 at 19:46
  • ...so what do you get if you print_r($_REQUEST);? Commented Oct 19, 2011 at 20:47

1 Answer 1

1

Try this:

At the client side:

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much. Mistake was simple.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.