PHP 使用 Fsockopen 发布数据

标签 php sockets 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

关于PHP 使用 Fsockopen 发布数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2367458/

相关文章:

php - 安装 PHP PDO 的 zlib 目录

php - getDoctrine() 在 FOSUserBundle symfony2 中不起作用

python - 仅在可用时在 python 套接字中接收数据

java - 检测服务器套接字关闭

php - PHP 中的文件资源持久性

php - 刷新页面时,fsockopen 并不总是执行 mysql 查询

javascript - 如何在php函数中以数组形式返回

php - 数据库查询: Select row where and where

mysql - 通过 PhpStorm 进行 SSH 隧道 MySQL 连接和套接字连接

php - 我在检查服务器状态时遇到一些问题