Check out Scrivo

Do you want to try out Scrivo? Then here's a demo for you that does not just get your feet wet but lets you plunge right in.

Contact us

For more information, please contact us. We're happy to help you out!

Next Sep 14 Previous

Item 547203

Consider the following code:

<?php

$result = file_get_contents("http://www.bogus.com", false,
    stream_context_create(
        array(
            "http" => array(
                "method" => "POST",
                "header" => "Content-type: application/x-www-form-urlencoded",
                "content" => base64_encode("This is the payload")
            )
        )
    )
);

?>

What will happen when it is executed?

A: A POST request will be performed.
B: You can't POST data this way: file_get_contents() is for getting not posting. Use the cURL extension if you want to post data to a server.
C: A POST request is attempted but the server returns status code 500 because the given payload was not encoded as stated in the Content-type header.
D: The call to file_get_contents() will raise an error.
E: There are no second and third parameters to file_get_contents(), so these will be ignored an a GET request will be performed.

Answer

This is a proper way to perform a POST request so A is the correct answer. No deliberate (syntax) errors were made, so answers D and E are false.

Although it still is common practice to use the cURL extension to do POST requests, there is absolutely no need to use an extra module just to do that. So answer B is not correct too.

Although the way the data was send doesn't make much sense, the server will not complain a bit. Therefore answer C is not correct. Actually the data send is accessible to the receiving script: a var_dump() of the $_POST array will look like:

array(1) {
  ["VGhpcyBpcyB0aGUgcGF5bG9hZA"]=>
  string(1) "="
}

[/code]

Which is actually a very nice new question: why does the posted variable have a value of '='?