【发布时间】:2014-06-02 09:26:16
【问题描述】:
我正在尝试寻找一种无 cURL 的方式来通过 http Web 请求将数据发布到第 3 方支付网关。我开发了以下代码,实际上它与接收页面成功通信,但显然没有发送 POST 数据。
<?php
function makeWebRequest()
{
//URL where to send the data via POST
$url = 'http://localhost/connect_to_gateway/receive.php';
//the actual data
$xml = '<?xml version="1.0" encoding="UTF-8"?>' .
'<test>' .
'Hi there!' .
'</test>';
$data = array('xml' => $xml);
//prepare the HTTP Headers
$content_type = 'text/xml';
$data = http_build_query($data);
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type: ' . addslashes($content_type) .'\r\n'
. 'Content-Length: ' . strlen($data) . '\r\n',
'content' => $data,
),
);
$context = stream_context_create($options);
/*send the data using a cURL-less method*/
$result = file_get_contents($url, false, $context);
echo 'file_get_contents<br/>';
var_dump($result); /* <=== POST DATA NOT ARRIVING AT DESTINATION (I only receive a string with "START- FINISH - ") */
echo '<br/><br/><br/><br/>';
}
//call the function
makeWebRequest();
?>
为了检查第 3 方页面未接收到数据的原因,我创建了自己的接收页面 (receive.php),并将请求发送到自己的脚本:
<?php
echo 'START- ';
if($_POST)
{
echo 'INSIDE- ';
echo htmlentities($_POST[0]);
}
echo 'FINISH -';
?>
我可以确认这是真的 :(。接收脚本没有收到 POST 数据,因为我从我自己的页面得到的响应是一个字符串,其值为:“START- FINISH-”。如果收到了 POST 数据,响应文本至少会包含单词INSIDE-。
你知道我做错了什么吗?
虽然我想专门将内容类型设置为“文本/xml”,但我也尝试了“应用程序/x-www-form-urlencoded”但仍然没有成功,$_POST 仍然是空的。我还尝试 (a) 在标头中省略 Content-Length,以及 (b) 直接发送 $xml 而不是 $data。
这个tutorial on brugbart.com 显示了一个与我相似的示例。这个forum post on sitepoint 提到了一些我仍然不明白的东西,即如果 PHP 是用 --with-curlwrappers 编译的(他在那里是什么意思?),标题应该作为一个简单的数组而不是纯文本发送。我解释站点点 cmets 的方式是这样的,但我仍然没有进展: $o
$options = array(
'http' => array(
'method' => 'POST',
'header' => array(
'Content-type' => addslashes($content_type),
'Content-Length' => strlen($data)),
'content' => $data,
),
);
任何帮助将不胜感激。
对于那些问我为什么要避免使用 cURL 的人,这是因为 libcurl 并不总是安装在每个人的服务器上,我正在尝试找到一种方法来实现相同的目标,而无需要求管理员安装 libcurl(如果未安装)原始安装..我正在尝试使用'vanilla php'。
其他类似这样的 stackoverflow 帖子没有帮助:
【问题讨论】:
标签: xml http-headers httpwebrequest file-get-contents postdata