Reputation: 3712
I am using fsockopen to connect and send data to a script. The problem is that no data is received on the receiving end as you can see in my output below, only empty array is printed. I've based my solution on Tamlyns answer here: PHP Post data with Fsockopen. I did' try his way of creating the post-parameters, no difference in the output.
My main script:
<?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);
?>
Output:
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
(
)
What's the problem and how do I fix it?
Upvotes: 0
Views: 3434
Reputation: 3712
This row
$out.= "Authorization: Basic ".$auth;
should have been
$out.= "Authorization: Basic ".$auth."\r\n";
There was something else which I haven't identified, but this code works (probably just some mixing up of variables when testing around):
<?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);
?>
Upvotes: 0
Reputation: 5022
There's a typo in your code:
$out.= 'Content-Length: '.strlen($params).'\r\n';
$out.= "Connection: Close\r\n\r\n";
Should be:
$out .= "Content-Length: ".strlen($params)."\r\n";
$out .= "Connection: close\r\n\r\n";
See how you've used single quotes around \r\n
? That means literally send '\r\n'
rather than interpret these as a Windows crlf
. The double quotes corrects this.
Upvotes: 2