HTTP Basic Authentication with PHP curl
When constructing a REST web service client in PHP, utilizing curl to establish authenticated requests might arise. Implementing HTTP basic authentication requires setting the necessary headers manually.
Solution:
To authenticate a request using HTTP basic, follow these steps:
Configure the CURLOPT_USERPWD option:
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
Example:
A comprehensive authenticated request could resemble 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);
The above is the detailed content of How Can I Implement HTTP Basic Authentication with PHP's cURL?. For more information, please follow other related articles on the PHP Chinese website!