Skip to content
Advertisement

XMLHttpRequest Send converted to PHP file_get_contents

So I’m trying to get the send data in an XHR to be put into the header in PHP’s file_get_contents.

Because I need the exact Referer header when sending the post request, I need to do it PHP file_get_contents with stream_context_create style.

I basically need this:

xhr.open('POST', 'https://example.com/test');
xhr.setRequestHeader('Referer','https://example.com');
xhr.send('{thing1: "abc", thing2: "def", thing3: "ghi"}');

turned into PHP, like this:

$url = "https://example.com/test";

$content = '{thing1: "abc", thing2: "def", thing3: "ghi"}';

$opts = ["http" => ["method" => "POST","header" => 
"Content-Type: application/json; charset=UTF-8rn".
"Referer: https://example.comrn".
"X-Requested-With: XMLHttpRequestrn"]];;

echo file_get_contents($url, true, stream_context_create($opts));

I do know that the X-Requested-With: XMLHttpRequest part is correct, but I don’t have a remote clue what the specific header value I could put in the $opts variable that could replace the xhr.send() function/just send the JSON data.

Advertisement

Answer

I don’t think xhr will allow you to set the Referer header it is set automatically.
On the server side you should be able to, see below.

$url = "https://example.com/test";

$content = json_encode([thing1 => "abc", thing2 => "def", thing3 => "ghi"]);

$opts = [
  "http" => [
    "method" => "POST", 
    "header" => [
      "Content-Type: application/json; charset=UTF-8",
      "Referer: https://example.com",
      "X-Requested-With: XMLHttpRequest"
    ],
    "content" => $content
  ]
]

echo file_get_contents($url, true, stream_context_create($opts));
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement