[英]HTTP POST from PHP, without cURL
I am using the example function given in 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;
}
?>
I also tried a similar approach using file_get_contents()
, like this: 我也尝试过使用
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);
With both these scripts, the response from the server script is the same, and it is the TEXT of the script.php
. 使用这两个脚本,来自服务器脚本的响应是相同的,它是
script.php
的TEXT。 The code of the server script is never begin executed, and the text content (the PHP code) of the script is being returned to the original script. 服务器脚本的代码永远不会开始执行,并且脚本的文本内容(PHP代码)将返回到原始脚本。
A little strange that it doesn't return all the text, but just certain pieces... I tried making a test script ( test.php
) that just contains: 有点奇怪,它不会返回所有文本,只是某些部分......我尝试制作一个只包含以下内容的测试脚本(
test.php
):
<?php
echo '{"a":1,"b":2,"c":3,"d":4,"e":5}';
?>
but that doesn't return anything from the POST request, so I didn't include that. 但是这不会从POST请求中返回任何内容,所以我没有包含它。 The
script.php
is a must longer script that does a lot of logic and MySQL queries then returns a JSON object. script.php
是一个必须更长的脚本,它执行大量逻辑和MySQL查询然后返回一个JSON对象。
The desired output will be to have the PHP code execute and return a JSON object (the way it works with ajax). 所需的输出是让PHP代码执行并返回一个JSON对象(它与ajax一起工作的方式)。
What am I doing wrong? 我究竟做错了什么?
You are trying access script localy. 您正在尝试访问脚本localy。 You must call it like any other external script like
你必须像任何其他外部脚本一样调用它
$refno = file_get_contents('http://yourhost/path/to/script/script.php',false,$context);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.