Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
667 views
in Technique[技术] by (71.8m points)

sockets - PHP Post data with 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);
}
?> 

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 );  
?>

The outcome is:

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
}

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...