Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use basic authorization in PHP curl

I am having problem with PHP curl request with basic authorization.

Here is the command line curl:

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

I have tried by setting curl header in following ways but it's not working

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

I get the response "authentication parameter in the request are missing or invalid" but I have used proper id and api_key which is working in command line curl (I tested)

Please help me.

like image 261
Al Amin Avatar asked Nov 19 '13 05:11

Al Amin


People also ask

How do you use the basic authentication in cURL?

To send basic auth credentials with Curl, use the "-u login: password" command-line option. Curl automatically converts the login: password pair into a Base64-encoded string and adds the "Authorization: Basic [token]" header to the request.

How can I get basic authorization token in PHP?

Where XXXXXX is your credentials in the form of username:password with base64 encoding. PHP automatically decodes and splits the username and password into special named constants: PHP_AUTH_USER with the username as a plain-text string. PHP_AUTH_PW with the password as a plain-text string.

How do I set basic authentication in HTTP header PHP?

Once the user has filled in a username and a password, the URL containing the PHP script will be called again with the predefined variables PHP_AUTH_USER , PHP_AUTH_PW , and AUTH_TYPE set to the user name, password and authentication type respectively. These predefined variables are found in the $_SERVER array.

How do I submit an Authorization header to basic?

Basic Auth: The client sends HTTP requests with the Authorization header that contains the word Basic, followed by a space and a base64-encoded(non-encrypted) string username: password. For example, to authorize as username / Pa$$w0rd the client would send. Note: Base64 encoding does not mean encryption or hashing!


2 Answers

Try the following code :

$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); 
like image 165
Suhel Meman Avatar answered Sep 28 '22 02:09

Suhel Meman


Can you try this,

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

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

like image 40
Krish R Avatar answered Sep 28 '22 01:09

Krish R