PHP使用Fsockopen发布数据

我试图使用fsockopen发布数据,然后返回结果.
这是我目前的代码:

<?php
$data="stuff=hoorah\r\n";
$data=urlencode($data);

$fp = fsockopen("www.website.com", 80, $errno, $errstr, 30);
if (!$fp) {
    echo "$errstr ($errno)<br />\n";
} else {
    $out = "POST /script.php HTTP/1.0\r\n";
    $out .= "Host: www.webste.com\r\n";
    $out .= 'Content-Type: application/x-www-form-urlencoded\r\n';
    $out .= 'Content-Length: ' . strlen($data) . '\r\n\r\n';
    $out .= "Connection: Close\r\n\r\n";
    fwrite($fp, $out);
    while (!feof($fp)) {
        echo fgets($fp, 128);
    }
    fclose($fp);
}
?> 

它应该回显页面,它回显页面,但这里是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 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 ( )

我有什么不对?为什么变量不发布其数据?

解决方法:

您的代码中存在许多小错误.这是一个经过测试和工作的片段.

<?php

$fp = fsockopen('example.com', 80);

$vars = array(
    'hello' => 'world'
);
$content = http_build_query($vars);

fwrite($fp, "POST /reposter.php HTTP/1.1\r\n");
fwrite($fp, "Host: example.com\r\n");
fwrite($fp, "Content-Type: application/x-www-form-urlencoded\r\n");
fwrite($fp, "Content-Length: ".strlen($content)."\r\n");
fwrite($fp, "Connection: close\r\n");
fwrite($fp, "\r\n");

fwrite($fp, $content);

header('Content-type: text/plain');
while (!feof($fp)) {
    echo fgets($fp, 1024);
}

然后在example.com/reposter.php上放这个

<?php print_r($_POST);

在运行时你应该得到类似的输出

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
上一篇:阿里云湖北区域服务商:架构设计包括哪些方面


下一篇:Day11 - D - Race to 1 Again LightOJ - 1038