F
F
furyon2018-02-03 23:21:13
PHP
furyon, 2018-02-03 23:21:13

How to emulate FormData request 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 figure out how to make the same request through PHP. I've tried different options, like this one:
$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);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
John Doe, 2018-02-03
@furyon

It is possible for example so, by means of 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;
}

You can also do this using HTTP v2:
<?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();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question