views:

9417

answers:

5

I found the following code on here that I think does what I want, but it doesn't work:

$host = "www.example.com";
$path = "/path/to/script.php";
$data = "data1=value1&data2=value2";
$data = urlencode($data);

header("POST $path HTTP/1.1\r\n");
header("Host: $host\r\n");
header("Content-type: application/x-www-form-urlencoded\r\n");
header("Content-length: " . strlen($data) . "\r\n");
header("Connection: close\r\n\r\n");
header($data);

I'm looking to post form data without sending users to a middle page and then using JavaScript to redirect them. I also don't want to use GET so it isn't as easy to use the back button.

Is there something wrong with this code? Or is there a better method?

Edit I was thinking of what the header function would do. I was thinking I could get the browser to post back to the server with the data, but this isn't what it's meant to do. Instead, I found a way in my code to avoid the need for a post at all (not breaking and just continuing onto the next case within the switch).

+4  A: 

The header function is used to send HTTP response headers back to the user (i.e. you cannot use it to create request headers.

May I ask why are you doing this? Why simulate a POST request when you can just right there and then act on the data someway? I'm assuming of course script.php resides on your server.

To create a POST request, open a up a TCP connection to the host using fsockopen(), then use fwrite() on the handler returned from fsockopen() with the same values you used in the header functions in the OP. Alternatively, you can use cURL.

Salaryman
Thxs, I was a little confused and yes, you are right, there was a better way within the script, no posting required.
Darryl Hein
+1  A: 

In addition to what Salaryman said, take a look at the classes in PEAR, there are HTTP request classes there that you can use even if you do not have the cURL extension installed in your PHP distribution.

cruizer
+3  A: 

You can also use cURL to send POST data.

alex
Examples of the cURL to use are at http://stackoverflow.com/questions/1586450/php-post-with-header-and-bad-header-problems/2008485
tog22
A: 
private function sendHttpRequest($host, $path, $query, $port=80){
    header("POST $path HTTP/1.1\r\n" );
    header("Host: $host\r\n" );
    header("Content-type: application/x-www-form-urlencoded\r\n" );
    header("Content-length: " . strlen($query) . "\r\n" );
    header("Connection: close\r\n\r\n" );
    header($query);
}

This will get you right away

That doesn't work for me - I get an (uninformative) Internal Server Error as soon as I add that code.
tog22
Why is there a `$port` in the parameter signature when it is not used?
alex
A: 

$port is used only in fsockopen(). The function should have the final line as a fsockopen() one.

Brin Hedrey