title: is `file_get_contents("php://input")` the only way to get post data from `fetch` and is it safe to use async- and hack-wise?
body: <p>I'm trying to rewrite my JQuery <code>$.post()</code> code via native <code>fetch()</code> function. And it seems like the only way to do it with PHP server code is using <code>file_get_contents(&quot;php://input&quot;)</code>.
  I do it like it is shown <a href="https://www.mikestreety.co.uk/blog/how-to-use-fetch-in-javascript-to-get-or-post-data/" rel="nofollow noreferrer">here</a> and <a href="https://codepen.io/dericksozo/post/fetch-api-json-php" rel="nofollow noreferrer">here</a>:</p>
  <p>js code:</p>
  <pre><code>fetch('/myscript.php', {
      method: 'post',
      mode: &quot;same-origin&quot;,
      credentials: &quot;same-origin&quot;,
      body: JSON.stringify({par1:par1, par2:par2})
  }).then(response =&gt; response.text())
  .then(output =&gt; {
    // do stuff
  });
  </code></pre>
  <p>myscript.php:</p>
  <pre><code>$input = json_decode(file_get_contents('php://input'), true);
  // do stuff with $input['par1'], $input['par2']
  echo $output;
  </code></pre>
  <p>There are two things which makes me worried:</p>
  <ol>
  <li><p>The project has more than one fetch call like this. What if two fetch functions are called simultaneously with two different php script files? They both will access <code>php://input</code> at the same time. Won't it lead to a conflict?</p>
  </li>
  <li><p>With <code>$.post()</code> I was able to check if <code>myscript.php</code> hasn't been called directly by a hacker with this line of code:</p>
  <p><code>if ($_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest') die('Hack attempt!');</code></p>
  <p>but with the new approach <code>$_SERVER['HTTP_X_REQUESTED_WITH']</code> is undefined for some reason. Is there a way to ensure <code>myscript.php</code> is called with fetch or <code>php://input</code> ensures it automatically?</p>
  </li>
  <li><p><code>fetch</code> is pretty modern function, but <code>json_decode(file_get_contents('php://input'), true)</code> looks pretty weird and intended for some other use case. Isn't there a better way to fetch data from a php-based server?</p>
  </li>
  </ol>