1

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.

5
  • Can you get any error information from the remote server? That should be your very first step Commented Sep 18, 2013 at 1:11
  • 1
    Can you set curl_setopt($ch, CURLOPT_VERBOSE, TRUE) as well and check? Commented Sep 18, 2013 at 1:12
  • @KaranAshar: I've just added the result of that to the end of the question. Commented Sep 18, 2013 at 1:32
  • Try adding curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); Commented Sep 18, 2013 at 3:19
  • @subroutines: Thanks for the idea; unfortunately I get the same response from the server. Commented Sep 18, 2013 at 14:33

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.