web-dev-qa-db-fra.com

Comment utiliser l'autorisation de base dans PHP curl

J'ai un problème avec PHP demande de curl avec autorisation de base.

Voici la ligne de commande curl:

curl -H "Accept: application/product+xml" "https://{id}:{api_key}@api.domain.com/products?limit=1&offset=0"

J'ai essayé en mettant l'en-tête curl de la manière suivante, mais cela ne fonctionne pas

Authorization: Basic id:api_key
or 
Authorization: Basic {id}:{api_key}

Je reçois la réponse "paramètre d'authentification dans la demande manquant ou invalide" mais j'ai utilisé les identifiants et api_key appropriés qui fonctionnent dans curl à la ligne de commande (j'ai testé)

Aidez-moi, s'il vous plaît.

47
Al Amin

Essayez le code suivant:

$username='ABC';
$password='XYZ';
$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);
125
Suhel Meman

Pouvez-vous essayer ceci,

 $ch = curl_init($url);
 ...
 curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);  
 ...

REF: http://php.net/manual/en/function.curl-setopt.php

7
Krish R