How to use the file_get_contents() function to make an HTTP request from PHP

In a previous post I talked about using the HttpRequest object and functions in the PECL_HTTP extension to make HTTP requests from PHP. In some cases you may be limited to using functionality built into the PHP core. The file_get_contents() function has less features than the PECL_HTTP extension but it is built into PHP 4.3 and up. Here is an example of using it to retrieve the landing page at www.example.com:

<?php
 
echo file_get_contents("http://www.example.com");
 
?>

Someone hit that easy button.

The file_get_contents() functions as well as many other PHP file functions implement a streams abstraction layer largely conceived by Mr. Wez Furlong. This abstraction layer is what enables many of the PHP file functions to access network resources. Given this functionality “file” seems a misnomer.

The file_get_contents() function uses an HTTP GET request but what if you want to do a POST without using cURL or the PECL_HTTP extension? Furlong posted an article here on how to do just that.

This next code example uses the file_get_contents() function again but this time a few options are set first using the stream_context_create() function:

<?php
 
$http_options = stream_context_create(array(
    'http' => array(
        'user_agent' => "Mark's Browser",
        'max_redirects' => 3)));
echo file_get_contents("http://www.example.com", false, $http_options);
 
?>

Note that the array passed to the stream_context_create() function can also be used to specify a POST method, which is how Furlong does so in his blog post.

There is still yet another way to make an HTTP request from PHP that I haven’t covered yet using the PHP built-in cURL functions. I will cover these in a separate blog post.

Leave a Reply