PHP 使用 Fsockopen 发布数据 [英] PHP Post data with Fsockopen
问题描述
我正在尝试使用 fsockopen 发布数据,然后返回结果.这是我当前的代码:
I am attempting to post data using fsockopen, and then returning the result. Here is my current code:
<?php
$data="stuff=hoorah
";
$data=urlencode($data);
$fp = fsockopen("www.website.com", 80, $errno, $errstr, 30);
if (!$fp) {
echo "$errstr ($errno)<br />
";
} else {
$out = "POST /script.php HTTP/1.0
";
$out .= "Host: www.webste.com
";
$out .= 'Content-Type: application/x-www-form-urlencoded
';
$out .= 'Content-Length: ' . strlen($data) . '
';
$out .= "Connection: Close
";
fwrite($fp, $out);
while (!feof($fp)) {
echo fgets($fp, 128);
}
fclose($fp);
}
?>
应该是回显页面,也是回显页面,但是这里是script.php的脚本
It is supposed to echo the page, and it is echoing the page, but here is the script for script.php
<?php
echo "<br><br>";
$raw_data = $GLOBALS['HTTP_RAW_POST_DATA'];
parse_str( $raw_data, $_POST );
//test 1
var_dump($raw_data);
echo "<br><br>":
//test 2
print_r( $_POST );
?>
结果是:
HTTP/1.1 200 OK 日期:2010 年 3 月 2 日,星期二22:40:46 GMT 服务器:Apache/2.2.3(CentOS) X-Powered-By: PHP/5.2.6内容长度:31 连接:关闭内容类型:文本/html;字符集=UTF-8string(0) "" 数组 ( )
HTTP/1.1 200 OK Date: Tue, 02 Mar 2010 22:40:46 GMT Server: Apache/2.2.3 (CentOS) X-Powered-By: PHP/5.2.6 Content-Length: 31 Connection: close Content-Type: text/html; charset=UTF-8 string(0) "" Array ( )
我有什么问题?为什么变量不发布其数据?
What do I have wrong? Why isn't the variable posting its data?
推荐答案
您的代码中有许多小错误.这是一个经过测试且有效的片段.
There are many small errors in your code. Here's a snippet which is tested and works.
<?php
$fp = fsockopen('example.com', 80);
$vars = array(
'hello' => 'world'
);
$content = http_build_query($vars);
fwrite($fp, "POST /reposter.php HTTP/1.1
");
fwrite($fp, "Host: example.com
");
fwrite($fp, "Content-Type: application/x-www-form-urlencoded
");
fwrite($fp, "Content-Length: ".strlen($content)."
");
fwrite($fp, "Connection: close
");
fwrite($fp, "
");
fwrite($fp, $content);
header('Content-type: text/plain');
while (!feof($fp)) {
echo fgets($fp, 1024);
}
然后在example.com/reposter.php把这个
And then at example.com/reposter.php put this
<?php print_r($_POST);
运行时你应该得到类似的输出
When run you should get output something like
HTTP/1.1 200 OK
Date: Wed, 05 Jan 2011 21:24:07 GMT
Server: Apache
X-Powered-By: PHP/5.2.9
Vary: Host
Content-Type: text/html
Connection: close
1f
Array
(
[hello] => world
)
0
这篇关于PHP 使用 Fsockopen 发布数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!