Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you POST to a page using the PHP header() function?

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).

like image 604
Darryl Hein Avatar asked Mar 17 '09 05:03

Darryl Hein


People also ask

What is the header () function in PHP?

The header() function is an predefined PHP native function. With header() HTTP functions we can control data sent to the client or browser by the Web server before some other output has been sent. The header function sets the headers for an HTTP Response given by the server.

What is the use of header () in PHP browser handling power?

PHP | header() Function. The header() function is an inbuilt function in PHP which is used to send a raw HTTP header. The HTTP functions are those functions which manipulate information sent to the client or browser by the Web server, before any other output has been sent.

What does the function header sent in PHP return?

The headers_sent() function will put the PHP source file name and line number where output started in the file and line variables if the file and line parameters are set. Return Value: This function returns True if headers has been sent and false otherwise.

Where is the header PHP?

php File in a Code Editor. To find the file and edit it yourself go to wp-content > themes > your-theme-name > header. php. You can then open it in a code editor and make any changes you need to.


3 Answers

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.

like image 173
Salaryman Avatar answered Sep 22 '22 17:09

Salaryman


The answer to this is very needed today because not everyone wants to use cURL to consume web services. Also PHP does allow for this using the following code

function get_info()
{
    $post_data = array(
        'test' => 'foobar',
        'okay' => 'yes',
        'number' => 2
    );

    // Send a request to example.com
    $result = $this->post_request('http://www.example.com/', $post_data);

    if ($result['status'] == 'ok'){

        // Print headers
        echo $result['header'];

        echo '<hr />';

        // print the result of the whole request:
        echo $result['content'];

    }
    else {
        echo 'A error occured: ' . $result['error'];
    }

}

function post_request($url, $data, $referer='') {

    // Convert the data array into URL Parameters like a=b&foo=bar etc.
    $data = http_build_query($data);

    // parse the given URL
    $url = parse_url($url);

    if ($url['scheme'] != 'http') {
        die('Error: Only HTTP request are supported !');
    }

    // extract host and path:
    $host = $url['host'];
    $path = $url['path'];

    // open a socket connection on port 80 - timeout: 30 sec
    $fp = fsockopen($host, 80, $errno, $errstr, 30);

    if ($fp){

        // send the request headers:
        fputs($fp, "POST $path HTTP/1.1\r\n");
        fputs($fp, "Host: $host\r\n");

        if ($referer != '')
            fputs($fp, "Referer: $referer\r\n");

        fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
        fputs($fp, "Content-length: ". strlen($data) ."\r\n");
        fputs($fp, "Connection: close\r\n\r\n");
        fputs($fp, $data);

        $result = '';
        while(!feof($fp)) {
            // receive the results of the request
            $result .= fgets($fp, 128);
        }
    }
    else {
        return array(
            'status' => 'err',
            'error' => "$errstr ($errno)"
        );
    }

    // close the socket connection:
    fclose($fp);

    // split the result header from the content
    $result = explode("\r\n\r\n", $result, 2);

    $header = isset($result[0]) ? $result[0] : '';
    $content = isset($result[1]) ? $result[1] : '';

    // return as structured array:
    return array(
        'status' => 'ok',
        'header' => $header,
        'content' => $content);

}
like image 21
Carl McDade Avatar answered Sep 25 '22 17:09

Carl McDade


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.

like image 20
cruizer Avatar answered Sep 24 '22 17:09

cruizer