PHP: Get contents from a page protected by password

Retrieving the contents of a webpage in PHP5 is really easy these days. You simply make a call to file_get_contents() and it automatically handles the request and parsing for you. It even works for local files!

Now, what if the page you're trying to access requires authentication? Luckily, its not difficult to do this either.

// Set up the authentication information
$url = "";
$username = "administrator";
$password = "p455word";

// Set up the context stream
$context_info = array(
  'http' => array(
    'header' => "Authorization: Basic " . base64_encode("$username:$password")
$context = stream_context_create($context_info);

// Retrieve the page
$data = file_get_contents($url, false, $context);

The data scraped from the page should now be contained within the $data variable.

[ Source ]

Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog