PHP: Download Web Page using file_get_contents

You can use curl to download a webpage in PHP. It is also possible to download a web page using file_get_contents().

<?php

function downloadURL($URL) {
  $webpage = file_get_contents ($URL);
  return $webpage;
}

$webpage = downloadURL("http://www.mozilla.org/");
if ($webpage){
  echo $webpage;
}
else {
  echo "Error in downloading the webpagen";
}
?>

$ php download.php
<html>
....
</body>
</html>

In the above example, we try to download the web page of Mozilla. Let’s try to download a non existing web page

<?php

function downloadURL($URL) {
  $webpage = file_get_contents ($URL);
  return $webpage;
}

$webpage = downloadURL("http://www.mozilla.org/1");
if ($webpage){
  echo $webpage;
}
else {
  echo "Error in downloading the webpagen";
}
?>

We find the following error

$ php download.php

Warning: file_get_contents(http://www.mozilla.org/1): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found
 in /home/user/Documents/Dropbox/Personal/Programs/downloadWebpage.php on line 4
Error in downloading the webpage

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s