How do I make a request using HTTP basic authentication with PHP curl?


I'm building a REST web service client in PHP and at the moment I'm using curl to make requests to the service.

How do I use curl to make authenticated (http basic) requests? Do I have to add the headers myself?

2/23/2017 3:21:39 PM

Accepted Answer

You want this:

curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);  

Zend has a REST client and zend_http_client and I'm sure PEAR has some sort of wrapper. But its easy enough to do on your own.

So the entire request might look something like this:

$ch = curl_init($host);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/xml', $additionalHeaders));
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payloadName);
$return = curl_exec($ch);
2/12/2019 3:26:16 AM

CURLOPT_USERPWD basically sends the base64 of the user:password string with http header like below:

Authorization: Basic dXNlcjpwYXNzd29yZA==

So apart from the CURLOPT_USERPWD you can also use the HTTP-Request header option as well like below with other headers:

$headers = array(
    'Authorization: Basic '. base64_encode("user:password") // <---
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow