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-8\r\n".
"Referer: https://example.com\r\n".
"X-Requested-With: XMLHttpRequest\r\n"]];;
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.
CodePudding user response:
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));