Home > Backend Development > PHP Tutorial > How Can I Implement HTTP Basic Authentication with PHP's cURL?

How Can I Implement HTTP Basic Authentication with PHP's cURL?

Linda Hamilton
Release: 2024-12-18 06:28:14
Original
880 people have browsed it

How Can I Implement HTTP Basic Authentication with PHP's cURL?

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:

  1. Configure the CURLOPT_USERPWD option:

    curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
    Copy after login
  2. Optional: Utilize the Zend HTTP client or a compatible PEAR wrapper for convenience.

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

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!

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