How to make a request using HTTP basic authentication with PHP curl?

Spread the love

Sometimes, we want to make a request using HTTP basic authentication with PHP curl.

In this article, we’ll look at how to make a request using HTTP basic authentication with PHP curl.

How to make a request using HTTP basic authentication with PHP curl?

To make a request using HTTP basic authentication with PHP curl, we call curl_setopt to set some options before making the request.

For instance, we write

$ch = curl_init($host);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/xml', $additionalHeaders));
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payloadName);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$return = curl_exec($ch);
curl_close($ch);

to call curl_setopy to set the CURLOPT_HTTPHEADER to set some headers.

And then we set the CURLOPT_USERPWD to the $username . ":" . $password string which combines the username and password.

And then we call curl_exec with $ch which has the $host info.

We get the response with the object returned by curl_exec.

Conclusion

To make a request using HTTP basic authentication with PHP curl, we call curl_setopt to set some options before making the request.

Leave a Reply

Your email address will not be published.