<tutorialjinni.com/>

cURL Basic Auth Example

Posted Under: cURL, PHP, Shell, Tutorials on Feb 19, 2022
cURL Basic Auth Example
The HTTP 401 Unauthorized response status code indicates that the client request has not been completed because it lacks valid authentication credentials for the requested resource. The basic access authentication is a method for an HTTP client usually a web browser to provide a user name and password when making a request. In basic HTTP authentication, a request contains a header field in the form of Authorization: Basic , where credentials is the Base64 encoding of ID and password joined by a single colon :. HTTP Basic authentication (BA) implementation is the simplest technique for enforcing access controls to web resources because it does not require cookies, session identifiers, or login pages; rather, HTTP Basic authentication uses standard fields in the HTTP header.

PHP cURL Basic Authentication Example

There are two methods to do using using PHP and cURL, one is use CURLOPT_USERPWD and second is to send credentials via header.
$USERNAME="GUEST_USER";
$PASSWORD="PASSWORD";
$ch= curl_init();
curl_setopt($ch, CURLOPT_URL,"https://www.tutorialjinni.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_USERPWD, "$USERNAME:$PASSWORD");// Notice the colon :
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
$html = curl_exec($ch);
echo $html;
PHP cURL HTTP 401 Basic Authentication via Headers
$USERNAME="USER";
$PASSWORD="SECRETPASS";
$ch= curl_init();
curl_setopt($ch, CURLOPT_URL,"https://www.tutorialjinni.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, "Authorization: Basic ". base64_encode("$USERNAME:$PASSWORD"));
$html = curl_exec($ch);
echo $html;

cURL Basic Authentication via Shell

Passing credentials via Shell or Terminal is simple
https://USERNAME:PASSWORD@www.tutorialjinni.com/resource.html
Notice the colon : and @.


imgae