Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send a cURL POST without request data in PHP?

Tags:

http

post

php

curl

My goal is to send a POST request to a server and get the proper response.

Note: Angled brackets represent placeholders.

In Terminal, using the following code will provide me the desired response.

curl -u <user>:<pass> -H 'Content-Type: application/xml' -X POST https://<rest of url>

My current PHP looks something like this:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $uri); //$uri is the same that I use in terminal
curl_setopt($ch, CURLOPT_USERPWD,
    sprintf('%s:%s', $user, $pass)); //same as terminal user & pass
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$headers = array(
    'Content-Type: application/xml', //expect an xml response
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$curl_result = curl_exec($ch);

Using this PHP, I get a 400 Bad Request error.

The verbose information:

> POST <same url> HTTP/1.1
Authorization: Basic YWRtaW5Ac3Bhcms0NTEuY29tOnNwYXJrc29tZXRoaW5n
Host: <correct host>
Accept: */*
Content-Type: application/xml
Content-Length: -1
Expect: 100-continue

* HTTP 1.0, assume close after body
< HTTP/1.0 400 Bad request
< Cache-Control: no-cache
< Connection: close
< Content-Type: text/html

Why am I getting a 400 Bad Request error when I use PHP, but not when I use command line? How can I fix this issue so that I get my desired response using PHP?

like image 520
sparkpham Avatar asked Sep 10 '14 13:09

sparkpham


1 Answers

curl_setopt($ch, CURLOPT_POSTFIELDS, array());

After adding this line, I resolved my problem. In a way, this solution makes sense; but I don't understand why CURLOPT_POSTFIELDS is required. In the PHP documentation, this part should be included under CURLOPT_POST, unless this just accidentally works.

like image 148
sparkpham Avatar answered Sep 25 '22 19:09

sparkpham