【问题标题】:HTTP POST from PHP, without cURL来自 PHP 的 HTTP POST,没有 cURL
【发布时间】:2012-09-19 17:49:03
【问题描述】:

我正在使用this post中给出的示例函数:

<?php
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;
}
?>

我也尝试过使用file_get_contents() 的类似方法,如下所示:

$options = array(
  'http'=>array(
    'method'=>"POST",
    'header'=>
      "Accept-language: en\r\n".
      "Content-type: application/x-www-form-urlencoded\r\n",
    'content'=>http_build_query(
        array(
            'arg1'=>'arg_data_1',
            'oper'=>'get_data',
            'arg2'=>'arg_data_2',
            'id_number'=>'7862'
        ),'','&'
    )
));

$context = stream_context_create($options);
$refno = file_get_contents('/path/to/script/script.php',false,$context);

var_dump($refno);

对于这两个脚本,来自服务器脚本的响应是相同的,都是script.php 的文本。服务器脚本的代码永远不会开始执行,并且脚本的文本内容(PHP 代码)正在返回到原始脚本。

有点奇怪,它没有返回所有文本,而只是返回某些部分...我尝试制作一个仅包含以下内容的测试脚本 (test.php):

<?php
echo '{"a":1,"b":2,"c":3,"d":4,"e":5}';
?>

但这不会从 POST 请求中返回任何内容,所以我没有包含它。 script.php 是一个必须更长的脚本,它执行大量逻辑,MySQL 查询然后返回一个 JSON 对象。

所需的输出是让 PHP 代码执行并返回一个 JSON 对象(它与 ajax 一起工作的方式)。

我做错了什么?

【问题讨论】:

  • 你只是在本地读取文件——你完全绕过了网络服务器,所以 PHP 代码没有被处理成完成的内容。
  • 我在使用 curl 和访问本地计算机上的脚本时遇到了问题。看起来这与答案所暗示的问题相同。

标签: php post web


【解决方案1】:

您正在尝试本地访问脚本。 您必须像调用任何其他外部脚本一样调用它,例如

$refno = file_get_contents('http://yourhost/path/to/script/script.php',false,$context);

【讨论】:

    猜你喜欢
    • 2013-02-24
    • 1970-01-01
    • 1970-01-01
    • 2011-01-09
    • 1970-01-01
    • 2020-09-07
    相关资源
    最近更新 更多