- PHP: Using cURL with Basic HTTP Authentication.
- 401 Unauthorized.
- Using the CURLOPT_USERPWD option.
- Using CURLOPT_HTTPHEADER.
- PHP CURL With HTTP Basic Authentication (A Simple Example)
- TLDR – QUICK SLIDES
- TABLE OF CONTENTS
- PHP CURL WITH HTTP AUTH
- SERVER A) PHP CURL CALL
- SERVER B) PROTECTED FOLDER
- DOWNLOAD & NOTES
- SUPPORT
- EXAMPLE CODE DOWNLOAD
- EXTRA BITS & LINKS
- LINKS & REFERENCES
- INFOGRAPHIC CHEAT SHEET
- THE END
- Leave a Comment Cancel Reply
- Search
- Breakthrough Javascript
- Socials
- About Me
- How to make a PHP curl request with basic authentication
- PHP: Using cURL with Basic HTTP Authentication.
- 401 Unauthorized.
- Using the CURLOPT_USERPWD option.
- Using CURLOPT_HTTPHEADER.
PHP: Using cURL with Basic HTTP Authentication.
This is a short PHP tutorial on how to use cURL to make a Basic Access Authentication request. In this post, I will show you how to configure PHP’s cURL functions to access a web resource that is protected by basic HTTP authentication.
401 Unauthorized.
If you send a cURL request to a URL that is protected by HTTP authentication, the response will probably look something like this:
401 Unauthorized: You need a valid user and password to access this content.
The issue here is that the resource is protected and you did not provide a valid username and password. As a result, the server responded with a 401 Unauthorized response.
Using the CURLOPT_USERPWD option.
To solve this, we can use the CURLOPT_USERPWD option. This option allows us to tell cURL what username and password to use while making the request.
An example of it being used:
//The URL of the resource that is protected by Basic HTTP Authentication. $url = 'http://site.com/protected.html'; //Your username. $username = 'myusername'; //Your password. $password = 'mypassword'; //Initiate cURL. $ch = curl_init($url); //Specify the username and password using the CURLOPT_USERPWD option. curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password); //Tell cURL to return the output as a string instead //of dumping it to the browser. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //Execute the cURL request. $response = curl_exec($ch); //Check for errors. if(curl_errno($ch)) < //If an error occured, throw an Exception. throw new Exception(curl_error($ch)); >//Print out the response. echo $response;
In the example above, we set the username and password using the CURLOPT_USERPWD option. As a result, our cURL client will end up sending the following header:
Authorization: Basic bXl1c2VybmFtZTpteXBhc3N3b3Jk
- In some cases, the resource in question might be expecting a POST request. Therefore, you might need to change the request above from a GET request to a POST request.
- The CURLOPT_USERPWD option sends the username and password combination in a base64 format. This means that a combination of “MyUsername:MyPassword” will become “TXlVc2VybmFtZTpNeVBhc3N3b3Jk”. However, it is important to note that base64 does not make this request any more secure. Therefore, it is advisable that you configure both the cURL client and the server to use SSL. This is to prevent man-in-the-middle attacks.
- Other options may need to be configured depending on your situation. In other words, the code above might not work “straight out of the box”.
Using CURLOPT_HTTPHEADER.
Alternatively, you can use the CURLOPT_HTTPHEADER, which allows you manually create headers. In the example below, we manually set the Content-Type and Authorization headers:
//HTTP username. $username = 'myusername'; //HTTP password. $password = 'mypassword'; //Create the headers array. $headers = array( 'Content-Type: application/json', 'Authorization: Basic '. base64_encode("$username:$password") ); //Set the headers that we want our cURL client to use. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
The code above should be used in lieu of the CURLOPT_USERPWD option.
Hopefully, you found this guide to be useful!
PHP CURL With HTTP Basic Authentication (A Simple Example)
Welcome to a tutorial on how to do a PHP CURL call with HTTP basic authentication. Need to secure a server-to-server call without all the crazy encryption, verification, and login stuff? HTTP basic authentication is a good option.
To perform a PHP CURL call with HTTP basic authentication, we have to set the user and password in the CURL options.
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, «HTTP://SITE.COM»);
- curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
- curl_setopt($ch, CURLOPT_USERPWD, «USER:PASSWORD»);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- $result = curl_exec($ch);
- curl_close($ch);
That should cover the basics, but read on for an actual example.
TLDR – QUICK SLIDES
TABLE OF CONTENTS
PHP CURL WITH HTTP AUTH
All right, let us now get into the example of CURL with HTTP basic authentication.
SERVER A) PHP CURL CALL
// (C) CURL EXEC // NOTE: HTTP RESPONSE CODE 200 = OK $result = curl_exec($ch); if (curl_errno($ch)) < echo curl_error($ch); >else < $info = curl_getinfo($ch); if ($info["http_code"] != 200) < print_r($info); >else < echo $result; >> curl_close($ch);
- As in the introduction, all we need is to set CURL options ( CURLOPT_HTTPAUTH and CURLOPT_USERPWD ) accordingly.
- If you are having trouble with SSL ( https:// ), try disabling the peer verification – curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false) .
- Take note of the “fetch results” part, we can use curl_getinfo() to get more information on the server response. Importantly, check the http_code – A failed authentication will usually return 401 (unauthorized).
SERVER B) PROTECTED FOLDER
- Apache web servers come with a tool called htpasswd and we can use it to generate a user/password file – htpasswd -c «PATH/FOLDER/.htpasswd» USER .
- Next, create a .htaccess file in the folder that you want to protect.
- AuthType Basic
- AuthName «Password Required»
- AuthUserFile PATH/FOLDER/.htpasswd
- Require valid-user
DOWNLOAD & NOTES
Here is the download link to the example code, so you don’t have to copy-paste everything.
SUPPORT
600+ free tutorials & projects on Code Boxx and still growing. I insist on not turning Code Boxx into a «paid scripts and courses» business, so every little bit of support helps.
EXAMPLE CODE DOWNLOAD
Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
EXTRA BITS & LINKS
That’s all for the main tutorial, and here is a small section on some extras and links that may be useful to you.
LINKS & REFERENCES
INFOGRAPHIC CHEAT SHEET
THE END
Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!
Leave a Comment Cancel Reply
Search
Breakthrough Javascript
Take pictures with the webcam, voice commands, video calls, GPS, NFC. Yes, all possible with Javascript — Check out Breakthrough Javascript!
Socials
About Me
W.S. Toh is a senior web developer and SEO practitioner with over 20 years of experience. Graduated from the University of London. When not secretly being an evil tech ninja, he enjoys photography and working on DIY projects.
Code Boxx participates in the eBay Partner Network, an affiliate program designed for sites to earn commission fees by linking to ebay.com. We also participate in affiliate programs with Bluehost, ShareASale, Clickbank, and other sites. We are compensated for referring traffic.
How to make a PHP curl request with basic authentication
When accessing API request over PHP curl, some routes are authentication required. Also third party API mostly required to authenticate before accepting request. This can be done by Bearer or Basic authentication method.
In this article, we will see how to send PHP curl request on authentication protected url. You need to send user and password data with the request. Below example send the get request which requires basic authentication:
[email protected]'; $password = '123456'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_USERPWD, $username.':'.$password); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch);
You can also send curl request using Authorization header. Curl CURLOPT_USERPWD option basically send Authorization header with value of username:password in a base64 format. You can do it as below:
[email protected]'; $password = '123456'; $headers = array( 'Authorization: Basic '. base64_encode($username.':'.$password) ); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HEADER, 1); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch);
This way, you can also make curl request over the routes which requires authentication. If you like the article,like our Facebook page and follow us on Twitter.
PHP: Using cURL with Basic HTTP Authentication.
This is a short PHP tutorial on how to use cURL to make a Basic Access Authentication request. In this post, I will show you how to configure PHP’s cURL functions to access a web resource that is protected by basic HTTP authentication.
401 Unauthorized.
If you send a cURL request to a URL that is protected by HTTP authentication, the response will probably look something like this:
401 Unauthorized: You need a valid user and password to access this content.
The issue here is that the resource is protected and you did not provide a valid username and password. As a result, the server responded with a 401 Unauthorized response.
Using the CURLOPT_USERPWD option.
To solve this, we can use the CURLOPT_USERPWD option. This option allows us to tell cURL what username and password to use while making the request.
An example of it being used:
//The URL of the resource that is protected by Basic HTTP Authentication. $url = 'http://site.com/protected.html'; //Your username. $username = 'myusername'; //Your password. $password = 'mypassword'; //Initiate cURL. $ch = curl_init($url); //Specify the username and password using the CURLOPT_USERPWD option. curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password); //Tell cURL to return the output as a string instead //of dumping it to the browser. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //Execute the cURL request. $response = curl_exec($ch); //Check for errors. if(curl_errno($ch)) < //If an error occured, throw an Exception. throw new Exception(curl_error($ch)); >//Print out the response. echo $response;
In the example above, we set the username and password using the CURLOPT_USERPWD option. As a result, our cURL client will end up sending the following header:
Authorization: Basic bXl1c2VybmFtZTpteXBhc3N3b3Jk
- In some cases, the resource in question might be expecting a POST request. Therefore, you might need to change the request above from a GET request to a POST request.
- The CURLOPT_USERPWD option sends the username and password combination in a base64 format. This means that a combination of “MyUsername:MyPassword” will become “TXlVc2VybmFtZTpNeVBhc3N3b3Jk”. However, it is important to note that base64 does not make this request any more secure. Therefore, it is advisable that you configure both the cURL client and the server to use SSL. This is to prevent man-in-the-middle attacks.
- Other options may need to be configured depending on your situation. In other words, the code above might not work “straight out of the box”.
Using CURLOPT_HTTPHEADER.
Alternatively, you can use the CURLOPT_HTTPHEADER, which allows you manually create headers. In the example below, we manually set the Content-Type and Authorization headers:
//HTTP username. $username = 'myusername'; //HTTP password. $password = 'mypassword'; //Create the headers array. $headers = array( 'Content-Type: application/json', 'Authorization: Basic '. base64_encode("$username:$password") ); //Set the headers that we want our cURL client to use. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
The code above should be used in lieu of the CURLOPT_USERPWD option.
Hopefully, you found this guide to be useful!