Reputation: 121
I am simply trying to duplicate this curl command in PHP:
curl -X POST -H 'Content-Type: application/xml' -u username:password https://api.company.com/api/path
This is the PHP code I am using:
$ch = curl_init("https://api.company.com/api/path");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/xml"));
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch); // $response is null
$info = curl_getinfo($ch); // $info['http_code'] is 400
While my shell command is successful and I get data back from the server, this PHP code fails -- the server returns a 400 error. As far as I know, the PHP code and the shell command are effectively identical, so what's the difference I am missing?
Edit:
Here is the info I get from verbose mode:
* About to connect() to api.company.com port 443 (#0)
* Trying xxx.xxx.xxx.xxx...
* connected
* Connected to api.company.com (xxx.xxx.xxx.xxx) port 443 (#0)
* successfully set certificate verify locations:
* CAfile: /etc/pki/tls/certs/ca-bundle.crt
CApath: none
* SSL connection using AES256-SHA
* Server certificate:
* [...]
* SSL certificate verify ok.
* Server auth using Basic with user 'username'
> POST /api/path HTTP/1.1
Authorization: Basic [...]
Host: api.company.com
Accept: */*
Content-Type: application/xml
Content-Length: -1
Expect: 100-continue
< HTTP/1.1 400 BAD_REQUEST
< Content-Length: 0
< Connection: Close
<
* Closing connection #0
Edit 2
I tried adding the following to the script:
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
But this did not change the server's response.
Upvotes: 1
Views: 158
Reputation: 121
I figured out the missing piece. I needed to explicitly set CURLOPT_POSTFIELDS
to null:
curl_setopt($ch, CURLOPT_POSTFIELDS, null);
After adding that line, things now work just as they did with the shell command.
Upvotes: 1