tags:

views:

646

answers:

4

I've come across a dumbfounding issue with sending headers in PHP. I've spent about 45 minutes reading on SO and other sites and I can't come up with a legitimate reason for my problem.

I need to send a POST request to another server and I'm using the PHP header() function to set the values. I have sample code below.

    $server = 'http://fakedomain.com';
    $server_path = '/';
    $request = 'key=value&key2=value2';
    header("POST $server_path HTTP/1.1" );
    header("Host: $server\r\n" );
    header("Content-type: application/x-www-form-urlencoded\r\n" );
    header("Content-length: ".strlen($request)."\r\n" );
    header("Connection: close\r\n\r\n" );
    header($request);

I've tried a variety of options but each of them results in the same error in my log file

malformed header from script. Bad header=POST / HTTP/1.1: php5.cgi

I'm an experience PHP programmer who just hasn't had much need to manually send HTTP post requests.

I want the code to redirect the browser so that's why I decided to use this method.

Am I doing it right?

Is there some other way that is standard and I just don't know about?

+9  A: 

header() sends a response header.

It sounds like you want to make a request, on the back end.

So you probably want to use curl to make the request.

If when you're done processing the response, you want to send some kind of header to the user agent (browser), then header() would be appropriate.

timdev
It's nice when you can learn something new. Much appreciated.
Paulo
+1  A: 

The header functions relate to the headers returned to the client, I suggest you look into using cURL to do your post request: http://www.php.net/cURL

Scuzzy
A: 

If you want to redirect user to another page, you should use

header("Location: http://domain.com/some.other.page?x=y");

If you want the user to send POST variables to the redirect page you will need to use JavaScript.

<html>
<head>
<title>Redirect</title>
</head>
<body onload="document.myform.submit()">
<form name="myform" action="http://domain.com/some.other.page" method="POST">
<input type="hidden" name="x" value="y">
</form>
</body>
</html>
Tim
A: 

Expanding on timdev's answer, here's the cURL you'd use:

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://www.target.com/script.php");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "postvar1=value1&postvar2=value2&postvar3=value3");
curl_exec ($ch);
curl_close ($ch); 
?>
tog22