Pour authentifier une requête cURL en PHP, l’option à connaître est CURLOPT_USERPWD. Elle envoie un couple identifiant / mot de passe au format utilisateur:motdepasse.
Authentification basique
$ch = curl_init('https://exemple.com/api');
curl_setopt($ch, CURLOPT_USERPWD, 'utilisateur:motdepasse');
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
$reponse = curl_exec($ch);
if ($reponse === false) {
throw new RuntimeException(curl_error($ch));
}
curl_close($ch);L’option CURLOPT_RETURNTRANSFER à true renvoie le corps de la réponse dans $reponse au lieu de l’afficher directement.
Choisir la méthode d’authentification
CURLOPT_HTTPAUTH permet de préciser le type. Les plus courants :
CURLAUTH_BASIC: authentification HTTP basique (par défaut) ;CURLAUTH_DIGEST: authentification digest ;CURLAUTH_ANY: laisse cURL choisir selon ce que le serveur propose.
Et pour un token Bearer ?
Si l’API utilise un jeton plutôt qu’un couple utilisateur / mot de passe, on passe par un en-tête plutôt que par CURLOPT_USERPWD :
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $token,
]);