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

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


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);curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);$return = curl_exec($ch);curl_close($ch);


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(    'Content-Type:application/json',    'Authorization: Basic '. base64_encode("user:password") // <---);curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);


The most simple and native way it's to use CURL directly.

This works for me :

<?php$login = 'login';$password = 'password';$url = 'http://your.url';$ch = curl_init();curl_setopt($ch, CURLOPT_URL,$url);curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);curl_setopt($ch, CURLOPT_USERPWD, "$login:$password");$result = curl_exec($ch);curl_close($ch);  echo($result);