使用fsockopen发布数据,接收方没有收到数据

时间:2012-03-19 09:30:26

标签: php post fsockopen

我正在使用fsockopen连接并向脚本发送数据。问题是接收端没有收到数据,如下面的输出中所示,只打印空数组。我的解决方案基于Tamlyns在这里回答:PHP Post data with Fsockopen。我确实'尝试创建后置参数的方式,输出没有区别。

我的主要文字:

<?php
session_start();  

    $fp = fsockopen("192.168.1.107",    
          80,
          $errno, $errstr, 10);    

    $params = "smtp=posteddata\r\n";
    $params = urlencode($params);

    $auth = base64_encode("kaand:kaand123");

     if (!$fp) {
          return false;
      } else {
          error_log("4");
          $out = "POST /smic/testarea/fsockopen_print_post.php HTTP/1.1\r\n";      
          $out.= "Host: 192.168.1.107\r\n";      
          $out.= "Content-Type: application/x-www-form-urlencoded\r\n";
          $out.= "Authorization: Basic ".$auth;
          $out.= 'Content-Length: '.strlen($params).'\r\n';
          $out.= "Connection: Close\r\n\r\n";
          $out .= $params;

          fwrite($fp, $out);
          fflush($fp);

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

          fclose($fp);
      }        
?>

fsockopen_print_post.php:

<?php
session_start();

print_r($_POST);

$raw_data = $GLOBALS['HTTP_RAW_POST_DATA'];  
parse_str( $raw_data, $_POST );
print_r($_POST);
?>

输出:

HTTP/1.1 200 OK
Date: Mon, 19 Mar 2012 09:21:06 GMT
Server: Apache/2.2.15 (CentOS)
X-Powered-By: PHP/5.3.10
Set-Cookie: PHPSESSID=i4lcj5mn1ablqgekb1g24ckbg5; path=/
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Content-Length: 20
Connection: close
Content-Type: text/html; charset=UTF-8

Array
(
)
Array
(
)

问题是什么?如何解决?

2 个答案:

答案 0 :(得分:2)

您的代码中存在拼写错误:

$out.= 'Content-Length: '.strlen($params).'\r\n';
$out.= "Connection: Close\r\n\r\n";

应该是:

$out .= "Content-Length: ".strlen($params)."\r\n";
$out .= "Connection: close\r\n\r\n";

了解如何在\r\n周围使用单引号?这意味着直接发送'\r\n'而不是将其解释为Windows crlf。双引号纠正了这一点。

答案 1 :(得分:0)

这一行

 $out.= "Authorization: Basic ".$auth;

应该是

 $out.= "Authorization: Basic ".$auth."\r\n";

还有其他一些我没有确定的,但是这段代码可以工作(可能只是在测试时混淆了一些变量):

<?php
$fp = fsockopen('192.168.1.107', 80);
$vars = array(
'hello' => 'world'
);
$content = http_build_query($vars);
$auth = base64_encode("kaand:kaand123");
$out = "POST /smic/testarea/fsockopen_print_post.php HTTP/1.1\r\n";      
$out .= "Host: 192.168.1.107\r\n";      
$out .= "Content-Type: application/x-www-form-urlencoded\r\n";
$out .= "Authorization: Basic ".$auth."\r\n";
$out .= "Content-Length: ".strlen($content)."\r\n";
$out .= "Connection: close\r\n\r\n";
$out .= $content;

fwrite($fp,$out);

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