forms - Send Multipart/formdata with CURL/php

I am trying to fetch the results of a web page that is generated after a form submission. There are 2 inputs in the form: 1- Name of the town 2- Date. When I inspect the page on Chrome as to what headers are being sent, this is what I get:
------WebKitFormBoundarymHxte4apsmNuBb5n
Content-Disposition: form-data; name="town"
CENTER
------WebKitFormBoundarymHxte4apsmNuBb5n
Content-Disposition: form-data; name="Date_Start"
17-05-2020
------WebKitFormBoundarymHxte4apsmNuBb5n--
The boundary, which is in this case "mHxte4apsmNuBb5n" changes with every submission.
I tried this code to no avail:
function curl($url) {
//POST string
$postfields['town'] = 'CENTER';
$postfields['Date_Start'] = '17-05-2020';
$headers = array("Content-Type:multipart/form-data; boundary=gc0p4Jq0M2Yt08jU534c0p");
$options = Array(
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_FOLLOWLOCATION => TRUE,
CURLOPT_AUTOREFERER => TRUE,
CURLOPT_CONNECTTIMEOUT => 120,
CURLOPT_TIMEOUT => 120,
CURLOPT_MAXREDIRS => 10,
CURLOPT_USERAGENT => "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1a2pre) Gecko/2008073000 Shredder/3.0a2pre ThunderBrowse/3.2.1.8",
CURLOPT_URL => $url,
CURLOPT_CAINFO => dirname(__FILE__)."/cacert.pem",
CURLOPT_POSTFIELDS => $postfields,
CURLOPT_HTTPHEADER => $headers,
);
$ch = curl_init();
curl_setopt_array($ch, $options);
$data = curl_exec($ch);
curl_error($ch);
curl_close($ch);
return $data;
}
$scraped_page = curl("http://...");
echo $scraped_page;
Any help will be appreciated.
Answer
Solution:
I am not sure why you have all the CURLOPT_* in place, but they are not strictly required for what you want.
If I create a file on my localhost with the code below it works:
<?php
$data = filter_input_array( INPUT_POST );
if ( $data ) {
print_r( $data );
exit;
}
$url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$data = [
'town' => 'CENTER',
'Date_Start' => '17-05-2020',
];
$ch = curl_init( $url );
curl_setopt_array( $ch, [
CURLOPT_POSTFIELDS => $data,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_RESOLVE => [ $_SERVER['HTTP_HOST'] . ':80:127.0.0.1' ], // Only required on localhost
] );
$response = curl_exec( $ch );
echo false !== $response
? 'result: ' . $response
: curl_error( $ch );
Als, I am using curl_error, which might help you to find out what is going on when curl_exec fails.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: xml parsing error: no root element found
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.