MacBook avec code sur un bureau

PHP – CURL Authentication

To authenticate a cURL request in PHP, the option to know is CURLOPT_USERPWD. It sends a username / password pair in the user:password format.

Basic authentication

$ch = curl_init('https://example.com/api');
curl_setopt($ch, CURLOPT_USERPWD, 'user:password');
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);

$response = curl_exec($ch);

if ($response === false) {
    throw new RuntimeException(curl_error($ch));
}

curl_close($ch);

Setting CURLOPT_RETURNTRANSFER to true returns the response body in $response instead of printing it directly.

Choosing the authentication method

CURLOPT_HTTPAUTH lets you set the type. The most common ones:

  • CURLAUTH_BASIC: HTTP basic authentication (the default);
  • CURLAUTH_DIGEST: digest authentication;
  • CURLAUTH_ANY: lets cURL pick based on what the server offers.

What about a Bearer token?

If the API uses a token rather than a username / password pair, you send a header instead of CURLOPT_USERPWD:

curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Authorization: Bearer ' . $token,
]);

See also