【问题标题】:XMLHttpRequest Send converted to PHP file_get_contentsXMLHttpRequest 发送转换为 PHP file_get_contents
【发布时间】:2021-12-15 10:07:18
【问题描述】:

所以我试图将 XHR 中的发送数据放入 PHP 的 file_get_contents 的标头中。

因为我在发送 post 请求时需要确切的 Referer 标头,所以我需要使用 stream_context_create 样式的 PHP file_get_contents

我基本上需要这个:

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

变成了PHP,像这样:

$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));

我确实知道X-Requested-With: XMLHttpRequest 部分是正确的,但我不知道我可以在$opts 变量中放入什么可以替换xhr.send() 函数的特定标头值/只需发送JSON 数据。

【问题讨论】:

    标签: javascript php xmlhttprequest file-get-contents


    【解决方案1】:

    我认为 xhr 不会允许您设置自动设置的 Referer 标头。
    在服务器端你应该可以,见下文。

    $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));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-17
      • 1970-01-01
      • 1970-01-01
      • 2012-06-13
      • 1970-01-01
      • 2021-10-20
      • 2014-12-16
      • 1970-01-01
      相关资源
      最近更新 更多