Обработка HTTP-сообщения с массивом (без cURL) - PullRequest
0 голосов
/ 19 октября 2011
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;
}

Имеет ли массив POST:

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

Как получить отдельный элемент массива для отдельного PHP var?

Часть страницы обработчика данных POST:

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

Что не так?

1 Ответ

2 голосов
/ 20 октября 2011

Попробуйте:

На стороне клиента:

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

На стороне сервера:

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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...