Home >Backend Development >PHP Tutorial >Can PHP's `file_get_contents()` Send Custom HTTP Headers?
Can PHP's file_get_contents() Function Send HTTP Headers?
In PHP, file_get_contents() is a versatile file I/O function that allows you to retrieve the contents of URLs as well. However, there has been some confusion surrounding its ability to send HTTP headers.
Initially, file_get_contents() did not provide a direct way to send custom HTTP headers. It was commonly assumed that setting these headers through php.ini's user agent parameter was the only option.
However, upon further examination of the file_get_contents() documentation, it was discovered that HTTP headers can indeed be sent using the stream_context_create() function. Here's an example:
// Create a stream context with custom HTTP headers $opts = [ "http" => [ "method" => "GET", "header" => "Accept-language: en\r\n" . "Cookie: foo=bar\r\n" ] ]; // Create a stream context from the options $context = stream_context_create($opts); // Open the URL with the stream context $file = file_get_contents('http://www.example.com/', false, $context);
By following this approach, you can now send custom HTTP headers with file_get_contents(). It's important to note that this method has not been extensively tested, so you may encounter issues depending on the specific headers and server configurations.
The above is the detailed content of Can PHP's `file_get_contents()` Send Custom HTTP Headers?. For more information, please follow other related articles on the PHP Chinese website!