Basic Authentication in PHP curl
In PHP curl, you can encounter issues when attempting to utilize basic authentication. This article aims to resolve this problem by providing a detailed explanation and a working PHP code example.
Issue Details
The user encountered difficulties authenticating with basic authorization in PHP curl. Despite using the correct credentials in their command line curl, they received an "authentication parameter in the request are missing or invalid" error when attempting to set the curl header using the following methods:
Solution
The correct way to set the curl header for basic authentication in PHP is to use the following code:
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY); curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
Code Example
Here's a comprehensive PHP curl example that demonstrates basic authentication:
$username = 'ABC'; $password = 'XYZ'; $URL = ''; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $URL); curl_setopt($ch, CURLOPT_TIMEOUT, 30); // timeout after 30 seconds curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY); curl_setopt($ch, CURLOPT_USERPWD, "$username:$password"); $result = curl_exec($ch); $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); // get status code curl_close($ch);
By following these steps and utilizing the provided PHP code example, you should be able to effectively use basic authorization in PHP curl.
The above is the detailed content of How to Implement Basic Authentication Correctly in PHP Curl?. For more information, please follow other related articles on the PHP Chinese website!