我正在使用这篇文章中给出的示例函数:
<?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 一起工作的方式)。
我究竟做错了什么?