How to emulate FormData query from PHP?

Hello!

For example, the site has a code
form = new FormData();
form.append('cmd', 'getUsers');
form.append('id', '2');
$.ajax({
 processData: false,
 contentType: false,
 type: 'POST',
 url: "/ajax.php",
 data: form,
 success: function (data) {
...
}
});


I can not understand how to make the same request via PHP. Tried different options, like this:
$url = 'http://.../ajax.php';
$data = 'cmd=getUsers&id=2';

$context = stream_context_create([
 'http' => [
 'method' => 'POST',
 'header' => [
 'Content-type: application/x-www-form-urlencoded',
],
 'content' => $data
]
]);
echo file_get_contents($url , FALSE, $context);
June 8th 19 at 16:26
1 answer
June 8th 19 at 16:28
Solution
It is possible, for example, using Curl.

<?php

$curl = curl_init();

curl_setopt_array($curl, array(
 CURLOPT_URL =--> "/ajax.php",
 CURLOPT_RETURNTRANSFER => true,
 CURLOPT_ENCODING => "",
 CURLOPT_MAXREDIRS => 10,
 CURLOPT_TIMEOUT => 30,
 CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
 CURLOPT_CUSTOMREQUEST => "POST",
 CURLOPT_POSTFIELDS => "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"\r\n\r\nbar\r\n-----011000010111000001101001--\r\n",
 CURLOPT_HTTPHEADER => array(
 "content-type: multipart/form-data; boundary=---011000010111000001101001"
),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
 echo "cURL Error #:" . $err;
} else {
 echo $response;
}


And, you can so, with v2 HTTP:
<?php

$client = new http\Client;
$request = new http\Client\Request;

$body = new http\Message\Body;
$body--->addForm(array(
 'foo' => 'bar'
), NULL);

$request->setRequestUrl('/ajax.php');
$request->setRequestMethod('POST');
$request->setBody($body);

$client->enqueue($request)->send();
$response = $client->getResponse();

echo $response->getBody();
Thank you!

Used the first option, but still complements the field CURLOPT_HTTPHEADER element 'X-Requested-With: XMLHttpRequest' - dell1 commented on June 8th 19 at 16:31

Find more questions by tags AJAXJavaScriptjQueryPHP