0

I am attempting to send a newsletter registration request to ymlp.com with PHP cURL

An html form works well with this code (I am using ptsv2.com to test POSTing):

<form method="post" action="http://ptsv2.com/t/stacktest/post?id=abcdefghijk">
  <input class="text" size="20" name="EMA0" type="text" placeholder="Type your email..." />
  <input class="submit" value="Subscribe to Newsletter" type="submit" />
</form>

So I tried mimicking this code in a PHP cURL request with the following code:

<?php
$cURLConnection = curl_init('http://ptsv2.com/t/stacktest/post?id=abcdefghijk');
curl_setopt($cURLConnection, CURLOPT_RETURNTRANSFER, true);
curl_setopt($cURLConnection, CURLINFO_HEADER_OUT, true);    
curl_setopt($cURLConnection, CURLOPT_POST, true);
curl_setopt($cURLConnection, CURLOPT_POSTFIELDS, ['EMA0' => 'deleteme@gmail.com']);
curl_setopt($cURLConnection, CURLOPT_HTTPHEADER, array('application/x-www-form-urlencoded'));
$response = curl_exec($cURLConnection);
curl_close($cURLConnection);

And the request is received but the html form's post content type appears as 'application/x-www-form-urlencoded' while the cURL post content type is 'multipart/form-data; boundary=------------------------b9f916145e7d51d3'.

And in the form post both id and EMA0 appear as parameters, while in the cURL post id appears as parameter while EMA0 appears as Multipart Value.

Am I providing the headers correctly to cURL ?

Is there any other mistake in my cURL code?

Thank you

Jaume Mal
  • 546
  • 5
  • 21
  • Have a look at https://stackoverflow.com/questions/5224790/curl-post-format-for-curlopt-postfields, see if `http_build_query()` helps. – Nigel Ren May 10 '20 at 07:20
  • 1
    `CURLOPT_POST` will create the `application/x-www-form-urlencoded ` request. If you pass in an `Array` to `CURLOPT_POSTFIELDS` it changes the request to `multipart/form-data` so you should use `http_build_query(['EMA0' => 'deleteme@gmail.com'])` perhaps... – Professor Abronsius May 10 '20 at 07:22
  • If you're setting headers (which shouldn't be necessary here), you also have to include the _name_ of the header you want to set - i.e. `Content-Type: application/x-www-form-urlencoded` or `['Content-Type' => 'application/x-www-form-urlencoded']`. – MatsLindh May 10 '20 at 07:34

1 Answers1

1

Based on Curl documentation regarding the CURLOPT_POSTFIELDS:

This parameter can either be passed as a urlencoded string like 'para1=val1&para2=val2&...' or as an array with the field name as key and field data as value. If value is an array, the Content-Type header will be set to multipart/form-data.

So, you should pass the post fields as string (probably by using http_build_query function) to have application/x-www-form-urlencoded content type.

Thus no need to set the headers, but just:

curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(['EMA0'=>1]));
Ali Khalili
  • 1,504
  • 3
  • 18
  • 19