如何使用带有 PHP curl 的 HTTP 基本身份验证发出请求?

问题描述:

我正在用 PHP 构建一个 REST Web 服务客户端,目前我正在使用 curl 向服务发出请求.

I'm building a REST web service client in PHP and at the moment I'm using curl to make requests to the service.

如何使用 curl 发出经过身份验证的(http 基本)请求?我必须自己添加标题吗?

How do I use curl to make authenticated (http basic) requests? Do I have to add the headers myself?

你想要这个:

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

Zend 有一个 REST 客户端和 zend_http_client,我确信 PEAR 有某种包装器.但它很容易自己做.

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:

$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);