Tech Notes

Set the HTTP Authentication Header from a Client — PHP / cURL

Protect a REST API with HTTP Basic authentication in PHP, and call it with the right header or with cURL.

HTTP authentication is a basic way to restrict access to web resources, and it’s simple to implement for REST APIs. You can use the code below to do this in PHP.

if ( isset($_SERVER['PHP_AUTH_USER']) 
         && $_SERVER['PHP_AUTH_USER'] == 'admin' 
         && $_SERVER['PHP_AUTH_PW'] == 'password' )
        {
              // Login success
}
        else
        {
            header('WWW-Authenticate: Basic realm="My Realm" ' );
            header('HTTP/1.0 401 Unauthorized' );
            echo 'Authentication required';
            exit;
        }

To access an API protected by HTTP authentication, you can either set the header yourself as shown below or use cURL. Always use HTTPS with Basic authentication, because the credentials are only Base64-encoded, not encrypted.

// From browser
// http header:
"Authorization: Basic ". base64_encode("username:password");
// Set the below option for CURL
 curl_setopt($ch, CURLOPT_USERPWD,  'username:password');