• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
The Electric Toolbox Blog

The Electric Toolbox Blog

Linux, Apache, Nginx, MySQL, Javascript and PHP articles

  • Applications
  • FCKEditor
  • Apache
  • Windows
  • Contact Us
Home / Sending a username and password with PHP file_get_contents()

Sending a username and password with PHP file_get_contents()

Last week I looked at how send a username and password with PHP CURL. Using CURL is useful because you can examine the return information to see if the request was successful etc, but if your hosting provider doesn’t have CURL for PHP enabled then you can still attempt to get the file by using file_get_contents and passing the authentication as part of the $context parameter.

In the example below, $url is the web address you want to get data from, and $username and $password are the login credentials.

$context = stream_context_create(array(
    'http' => array(
        'header'  => "Authorization: Basic " . base64_encode("$username:$password")
    )
));
$data = file_get_contents($url, false, $context);

If the login details were incorrect, or you were attempting to access a password protected location and didn’t pass any credentials at all, you’ll see an error like this:

Warning: file_get_contents(...): failed to open stream: HTTP request failed! 
HTTP/1.1 401 Authorization Required in ... on line 4

In future posts in this series I’ll look at how to pass other headers along with a file_get_contents() request, for example how to send a form post. Again I would mention that it’s probably better and easier to do this with CURL but if you must then it’s possible with file_get_contents().

Check Out These Related posts:

  1. RFC 1321 – MD5 Message-Digest Algorithm
  2. jQuery: show plain text in a password field and then make it a regular password field on focus
  3. Show the headers only for a request with cURL
  4. Sending a username and password with PHP CURL

Filed Under: PHP

Primary Sidebar

Categories

  • Apache
  • Applications
  • Article
  • Case Studies
  • Email Servers
  • FCKEditor
  • HTML And CSS
  • Javascript
  • Linux/Unix/BSD
  • Microsoft SQL Server
  • Miscellaneous Postings
  • MySql
  • Networking
  • Nginx Web Server
  • Offsite Articles
  • OSX
  • PHP
  • Quick Tips
  • RFC – Request for Comments
  • SilverStripe
  • VMWare
  • VPN
  • Windows
  • WordPress

Recent Posts

  • Vim Show Line Numbers
  • Add User To Group Linux
  • Chmod 777 Tutorial
  • How to Copy Directory Linux
  • Linux create user

Copyright © 2021. ElectricToolBox. All Rights Reserved.

  • Contact Us
  • Copyright Info
  • Privacy Policy
  • Sitemap