By using this site you agree to the use of cookies by Brugbart and our partners.

Learn more

Performing HTTP GET Requests in PHP

Tutorial on how to get URLs with PHP fread and file_get_contents.

Edited: 2016-01-03 18:04

Next: Making POST Requests

This PHP Tutorial focuses on the use of fread and file_get_contents to download content from the web – in this Tutorial we will focus on the HTTP protocol, but it may also work for HTTPs – Using the methods covered in this Tutorial, requires that the fopen wrappers has been enabled, enabling the wrappers can be done by setting allow_url_fopen in php.ini to On.

Performing HTTP requests can be useful for many things. Logging in on other websites, simply getting the content of a webpage, or checking for new versions of a PHP application. This PHP Tutorial will show you how to perform simple requests over HTTP, we will show how to set request headers in a later Tutorial.

Using Fread to Download of get Files Over the web

It is also possible to read a web page, just remember that reading will stop after a packet is available, so you either have to use a function like stream_get_contents – similar to file_get_contents – or you can use a while loop to read the content in smaller chunks until the end of the file has been reached.

<?php
$handle = fopen("http://brugbart.com/", "rb");
$contents = stream_get_contents($handle);
fclose($handle);
?>
<?php
$handle = fopen("http://brugbart.com/", "rb");
$contents = '';
while (!feof($handle)) {
  $contents .= fread($handle, 8192);
}
fclose($handle);
echo $contents;
?>

In this case the last argument in the fread function is equal to the chunk size, this is usually not larger than 8192 (8*1024). Keep in mind that this can be larger or smaller, but may also be limited by the system PHP is running on – you can likely optimize your PHP scripts by not using a larger chunk-size than that of your storage device.

Using File_get_contents to get a Website URL

It may also be easier to use this method when reading a file over HTTP, as you do not have to think about reading in chunks – everything is handled by PHP.

<?php
$homepage = file_get_contents('http://brugbart.com/');
echo $homepage;
?>