Using Authentication And file_get_contents()
Published by philipnorton42 on Mon, 02/15/2010 - 23:00Using file_get_contents() to fetch the contents of a file is quite a common practice. This might be just to get the contents of a text file or to get the ImageCache module in Drupal to pre-cache images. The file_get_contents() function can get a local or remote file and is usually run like this.
$data = file_get_contents($url);
However, when trying to use this function to communicate with an authenticated server you will see the following error appearing.
1 2 | Warning: file_get_contents(http://www.example.com/test.php): failed to open stream: HTTP request failed! HTTP/1.1 401 Authorization Required in test.php on line 4 |
To get around this issue you will need to pass a third parameter to the file_get_contents() function that causes the function to use a context. This context will pass an additional Authorization header to the server and is created through a function called stream_context_create(). Here is all the code you need to use file_get_contents() in an authenticated manner.
1 2 3 4 5 6 7 8 9 | $username = 'username'; $password = 'password'; $context = stream_context_create(array( 'http' => array( 'header' => "Authorization: Basic " . base64_encode("$username:$password") ) )); $data = file_get_contents($url, false, $context); |
The second parameter is for the addition of a flag and is skipped here by using a null value, but false is also applicable. For more information about what flags are available see the file_get_contents() page on the PHP manual.
Comments
Very helpful.....where does
Rix (not verified) - Tue, 02/16/2010 - 16:46$url is a variable containing
philipnorton42 - Tue, 02/16/2010 - 16:51$url = 'http://www.example.com/';Thanks....I have added a
Rix (not verified) - Tue, 02/16/2010 - 17:04echo $data;so that the contents of the file are returned to the screen but, even without that, I am getting: Warning: file_get_contents() expects at most 2 parameters, 3 given in C:\php1.php on line 14 where line 14 is$data = file_get_contents($url, false, $context);Apologies if this is a stupid question.This error suggests that you
philipnorton42 - Tue, 02/16/2010 - 17:18echo phpversion();Ah... 4.4.1... which, I see
Rix (not verified) - Tue, 02/16/2010 - 17:33What if you are using HTTPS?
Anonymous (not verified) - Thu, 09/30/2010 - 22:25Hi there, I used your
muthuraj (not verified) - Fri, 11/19/2010 - 06:36Add new comment