Home >Backend Development >PHP Tutorial >Can file_get_contents() in PHP Send Custom HTTP Headers?
Customizing HTTP Headers with file_get_contents()
PHP's file_get_contents() function is a versatile tool for retrieving web resources. It's often used with limited options, leaving users to wonder about its full capabilities. In particular, sending custom HTTP headers with file_get_contents() has been a subject of debate.
Is it possible?
Yes, it is possible to send custom HTTP headers using file_get_contents(). This can be achieved by creating a stream context using stream_context_create() and setting the desired headers in the http option.
// Create a stream context with custom headers $opts = [ "http" => [ "method" => "GET", "header" => "Accept-language: en\r\nCookie: foo=bar\r\n" ] ]; $context = stream_context_create($opts); // Retrieve the web resource using the custom stream context $file = file_get_contents('http://www.example.com/', false, $context);
In this example, we set the "Accept-language" and "Cookie" headers, but you can add any valid HTTP headers as needed.
Alternative Approaches
While file_get_contents() with a custom stream context is a viable option, there are alternative functions available for sending custom HTTP headers.
The choice of which function to use depends on the specific requirements and preferences of your project.
The above is the detailed content of Can file_get_contents() in PHP Send Custom HTTP Headers?. For more information, please follow other related articles on the PHP Chinese website!