PHP cURL with Basic Authorization
PHP cURL offers a simplified method to establish basic authorization within HTTP requests. While this is often straightforward, implementing it correctly can be challenging.
In cases like yours, where command line cURL succeeds but its PHP counterpart fails, the issue often lies in properly setting the authorization header. You've attempted various formats like "Authorization: Basic {id}:{api_key}" and "Authorization: Basic id:api_key," but these may not adhere to the required syntax.
To rectify this, utilize the following code snippet:
$username='{id}'; $password='{api_key}'; $URL='<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);
In this revised code, we specify the username ($username) instead of "{id}" and password ($password) instead of "{api_key}". Additionally, we set CURLOPT_HTTPAUTH to CURLAUTH_ANY, enabling support for various authentication schemes, including basic authentication.
This approach allows for proper basic authorization through PHP cURL, resolving your issue and providing a more robust solution.
The above is the detailed content of How to Implement Basic Authorization with PHP cURL?. For more information, please follow other related articles on the PHP Chinese website!