-H: HTTP header to send to the server with a POST request. -d: Data to be sent to the server using a POST request. --user: Provide the username and password that will be used to authenticate the server.
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.
What is Basic Authentication?
Basic Authentication is a client authentication method built into the HTTP protocol that allows a client to provide a username and password to the server when accessing secure resources over HTTP. When requesting a protected resource, the client sends HTTP requests with an Authorization header that contains the word Basic followed by a space and a base64 encoded username: password string.
Basic Authentication is not the most secure method because other protocol sniffers can easily decrypt base64 encoded user credentials. For security reasons, the Basic Authentication method should only be used over secure HTTPS/SSL connections.
curl -X POST [URL]
-H "Content-Type: application/json"
-d "{post_data}"
--user "login:password"
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;