I often see the discussion cURL vs file_get_contents and most of the times you find this statement somewhere in the discussion:

“Use cURL because with file_get_contents you can’t set any headers or do POST request…”

I think people should use what they are more comfortable with but this statement is just not true. You can pass a stream context, created with stream_context_create, as third parameter and with this you can set stuff like headers and also the request method to use. Here’s how:

Setting headers

To create a stream context you have to set the options first. For this we’ll need an array like this:

$opts = array(
    "http" => array(
        "method"  => "GET",
        "headers" => "[header-name]: [header-value]\r\n" .
                     "[header-name]: [header-value]\r\n"
    )
);

With this you can set all the headers you like, just don’t forget to always add \r\n at the end of each header.

Then you just have to create the context from this array and pass it to file_get_contents.

$context = stream_context_create($opts);
$result = file_get_contents("http://www.domain.tld", false, $context);

That’s it, you’ve done a GET request with file_get_contents where you set some headers.

Doing a POST request

You might have a clue already by looking at the first example with the headers. Just set the ‘method’ part of the array to POST and you’re doing a POST request 😉 But with a POST request you normally send along some data. That’s also not a problem at all. Here’s an example of how you do it:

$data = http_build_query(
    array(
        "value1name" => "some_value",
        "value2name" => "another_value"
    )
);

$opts = array('http' =>
    array(
        "method' => "POST",
        "header" => "Content-type: application/x-www-form-urlencoded\r\n",
        "content" => $data
    )
);

$context = stream_context_create($opts);

$result = file_get_contents("http://www.domain.tld", false, $context);

In this example it’s url encoded data like it would be when submitting a form but it could also be JSON data or anything, you just have to set the Content-Type header right.

Conclusion

I don’t want to say cURL is bad in any way but there are two main reasons I prefer file_get_contents over cURL:

  • file_get_contents is a built in PHP function so no extra extensions needed
  • it’s way less complex than cURL

Sure, cURL is a useful tool but I think for the most cases where you need to do a HTTP request file_get_contents is enough to achieve what you want to achieve and it’s, in my opinion, way more easy to get your head around.

Cheers,

Mo