PHP file_get_contents() and setting request headers

后端 未结 7 1082
庸人自扰
庸人自扰 2020-11-22 14:29

With PHP, is it possible to send HTTP headers with file_get_contents() ?

I know you can send the user agent from your php.ini file. However

7条回答
  •  独厮守ぢ
    2020-11-22 14:40

    Actually, upon further reading on the file_get_contents() function:

    // Create a stream
    $opts = [
        "http" => [
            "method" => "GET",
            "header" => "Accept-language: en\r\n" .
                "Cookie: foo=bar\r\n"
        ]
    ];
    
    // DOCS: https://www.php.net/manual/en/function.stream-context-create.php
    $context = stream_context_create($opts);
    
    // Open the file using the HTTP headers set above
    // DOCS: https://www.php.net/manual/en/function.file-get-contents.php
    $file = file_get_contents('http://www.example.com/', false, $context);
    

    You may be able to follow this pattern to achieve what you are seeking to, I haven't personally tested this though. (and if it doesn't work, feel free to check out my other answer)

提交回复
热议问题