yknivag
yknivag

Reputation: 85

PHP cURL - How do I send the body of the request?

I have a problem trying to post a request to an API using PHP. I have no control over the API server and must send the data in the format they are requesting. Their only real documentation is the following example for the CLI:

curl -X POST 'http://username:[email protected]/foo/bar?param1=false&param2=0' -d 'Hello World!'

Trying to put this into PHP, I have replicated most of it, I think, with the code below:

$ch = curl_init();
$username="username";
$password="password";
$data="Hello World!";
$url = "http://" . $username . ":" . $password . "@domain.tld";
$postvars = array( "param1"=>"false", "param2"=>0 );
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS,$postvars);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT ,3);
curl_setopt($ch,CURLOPT_TIMEOUT, 20);
$response = curl_exec($ch);
curl_close ($ch);

but I cannot work out where the data part goes? How do I send the body of the request (the part after the -d?

I cannot see anything in the PHP cURL documentation that indicates how the body of the request should be formed.

Upvotes: 1

Views: 480

Answers (3)

TheMisir
TheMisir

Reputation: 4279

You need to post body data using CURLOPT_POSTFIELDS option and append parameters to url instead of setting as post fields.

So, your code will be:

$ch = curl_init();
$username = "username";
$password = "password";
$data = "Hello World!";

$url = "http://" . $username . ":" . $password . "@domain.tld";
$params = array( "param1"=>"false", "param2"=>0 );

$url .= "?" . http_build_query($params);

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
$response = curl_exec($ch);
curl_close($ch);

Upvotes: 3

Tiago Mateus
Tiago Mateus

Reputation: 354

Regarding the POST fields, you need the CURLOPT_POSTFIELDS option.

Example:

CURLOPT_POSTFIELDS => array('var1' => 1,'var2' => 2)

About the username and password, I would advice you to use the CURLOPT_USERPWD.

Example:

CURLOPT_USERPWD => "$username:$password"

Upvotes: 0

majidarif
majidarif

Reputation: 20015

Using CURLOPT_POSTFIELDS like:

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'http://username:[email protected]/foo/bar?param1=false&param2=0');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "Hello World!");
curl_setopt($ch, CURLOPT_POST, 1);

$headers = array();
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$result = curl_exec($ch);
if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
}
curl_close ($ch);

Upvotes: 2

Related Questions