Home >Backend Development >PHP Tutorial >How to Implement HTTP Basic Authentication with PHP cURL?
HTTP Basic Authentication with PHP cURL
When creating HTTP requests to web services with cURL, you may encounter the need to provide authentication. HTTP basic authentication is a simple method of authenticating users by passing their username and password in the request header. This article demonstrates how to implement HTTP basic authentication using PHP cURL.
Creating the Authentication Header
To authenticate using cURL, you must set the CURLOPT_USERPWD option. This option takes a string in the following format:
curl_setopt($ch, CURLOPT_USERPWD, 'user:password');
Setting Additional Request Options
In addition to the authentication header, you may need to specify additional request options, such as:
Example Code
Here's an example script that makes an authenticated request to a web service:
$ch = curl_init($host); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/xml', 'Additional-Header: value')); curl_setopt($ch, CURLOPT_HEADER, 1); curl_setopt($ch, CURLOPT_USERPWD, 'user: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 to Implement HTTP Basic Authentication with PHP cURL?. For more information, please follow other related articles on the PHP Chinese website!