I'm building a REST web service client in PHP and at the moment I'm using curl to make requests to the service.
How do I use curl to make authenticated (http basic) requests? Do I have to add the headers myself?
I'm building a REST web service client in PHP and at the moment I'm using curl to make requests to the service.
How do I use curl to make authenticated (http basic) requests? Do I have to add the headers myself?
Michael Dowling's very actively maintained Guzzle is a good way to go. Apart from the elegant interface, asynchronous calling and PSR compliance, it makes the authentication headers for REST calls dead simple:
See the docs.
Unlike SOAP, REST isn't a standardized protocol so it's a bit difficult to have a "REST Client". However, since most RESTful services use HTTP as their underlying protocol, you should be able to use any HTTP library. In addition to cURL, PHP has these via PEAR:
HTTP_Request2
which replaced
HTTP_Request
A sample of how they do HTTP Basic Auth
The also support Digest Auth
CURLOPT_USERPWD
basically sends the base64 of theuser:password
string with http header like below:So apart from the
CURLOPT_USERPWD
you can also use theHTTP-Request
header option as well like below with other headers:For those who don't want to use curl:
You want this:
Zend has a REST client and zend_http_client and I'm sure PEAR has some sort of wrapper. But its easy enough to do on your own.
So the entire request might look something like this:
The most simple and native way it's to use CURL directly.
This works for me :