StackKev
StackKev

Reputation: 5

PHP curl is not parsing POST data

So i am trying to send a HTTPS POST request to a website but curl is not setting my post data nor my headers. Here is my code(i changed the domain and values):

<?php

//Create connection
$ch = curl_init();

//Set the headers
$headers = array();
$headers[] = "Connection: Keep-Alive";
$headers[] = "Host: website.com";
$headers[] = "Content-Type: application/x-www-form-urlencoded";
$headers[] = "Something: Something_Data";

//Set the POST data
$headers = array();
$headers[] = "Connection: Keep-Alive";
$headers[] = "Host: website.com";
$headers[] = "Content-Type: application/x-www-form-urlencoded";
$headers[] = "Something: Something_Data";

// Configure the request (HTTPS)
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_URL, "https://website.com/test");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, "MyUserAgentHere");
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_POST, 1); //just to be sure...

//Set the POST data and Headers
curl_setopt($ch, CURLOPT_POSTFIELDS, urlencode("DATA1=VAL1&DATA2=VAL2")); 
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); 

$result=curl_exec($ch);
echo $result;

curl_close($ch);
?>

So basically i'm trying to send a HTTPS POST request to https://website.com/test". The request is sent and i get an answer but for some reasons it doesn't parse the POST data nor the Headers.

Here is my request in fiddler:

POST https://website.com/test HTTP/1.1
Host: website.com

Here is the answer from the request:

HTTP/1.1 400 Bad Request
Date: Fri, 06 Nov 2015 00:57:15 GMT
Server: Apache
Cache-Control: no-store
Pragma: no-cache
Connection: close
Content-Type: application/json;charset=UTF-8
Content-Length: 158

{"error":"unsupported DATA1"}

As you can see, the POST data and the headers are not set in my request for some reason. I have no idea why curl is not setting my headers and my post fields.

Infos: I am using XAMPP with php5.

Upvotes: 0

Views: 1559

Answers (1)

Barmar
Barmar

Reputation: 782499

You shouldn't URL-encode the entire parameter string, that will encode the = and & so they're no longer delimiters. You should just encode the values.

curl_setopt($ch, CURLOPT_POSTFIELDS, 'DATA1=' . urlencode($val1) . '&DATA2' . urlencode($val2));

You can use an array instead, and cURL will do the encoding for you.

curl_setopt($ch, CURLOPT_POSTFIELDS, array('DATA1' => $val1, 'DATA2' => $val2));

If you use the array mechanism, remove the Content-type: application/x-www-form-urlencoded header, because cURL sends it in multipart/form-data format.

Upvotes: 2

Related Questions