来自PHP的HTTP POST,无cURL [英] HTTP POST from PHP, without cURL
问题描述
我正在使用此中提供的示例函数帖子:
<?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()
的类似方法,如下所示:
I also tried a similar approach using file_get_contents()
, like this:
$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
的TEXT.服务器脚本的代码永远不会开始执行,并且脚本的文本内容(PHP代码)将返回到原始脚本.
With both these scripts, the response from the server script is the same, and it is the TEXT of the script.php
. 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.
有些奇怪,它不会返回所有文本,而只是返回某些片段...我试图制作一个仅包含以下内容的测试脚本(test.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:
<?php
echo '{"a":1,"b":2,"c":3,"d":4,"e":5}';
?>
但这从POST请求中不返回任何内容,因此我没有包含该内容. script.php
是一个必须更长的脚本,它执行很多逻辑,MySQL查询然后返回一个JSON对象.
but that doesn't return anything from the POST request, so I didn't include that. The script.php
is a must longer script that does a lot of logic and MySQL queries then returns a JSON object.
所需的输出将是使PHP代码执行并返回JSON对象(与ajax一起工作的方式).
The desired output will be to have the PHP code execute and return a JSON object (the way it works with ajax).
我在做什么错了?
推荐答案
您正在尝试访问脚本语言环境. 您必须像其他任何外部脚本一样调用它
You are trying access script localy. You must call it like any other external script like
$refno = file_get_contents('http://yourhost/path/to/script/script.php',false,$context);
这篇关于来自PHP的HTTP POST,无cURL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!