Home > Backend Development > PHP Tutorial > How to Implement Basic Authentication Correctly in PHP Curl?

How to Implement Basic Authentication Correctly in PHP Curl?

Patricia Arquette
Release: 2024-11-12 08:25:02
Original
1051 people have browsed it

How to Implement Basic Authentication Correctly in PHP Curl?

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:

  • Authorization: Basic id:api_key
  • Authorization: Basic {id}:{api_key}

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");
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template