Home > Backend Development > PHP Tutorial > How Can I Send HTTP Headers with PHP's file_get_contents()?

How Can I Send HTTP Headers with PHP's file_get_contents()?

Patricia Arquette
Release: 2024-12-11 11:15:09
Original
821 people have browsed it

How Can I Send HTTP Headers with PHP's file_get_contents()?

Sending HTTP Headers with PHP's file_get_contents()

Although the file_get_contents() function in PHP does not offer direct support for sending HTTP headers, there are alternative approaches to achieve this.

One method is to create a stream context and configure the HTTP headers within it. This involves setting up an array called $opts that specifies the HTTP method (GET in this example), and adding the desired headers in the header key. For example:

// Create a stream
$opts = [
    "http" => [
        "method" => "GET",
        "header" => "Accept-language: en\r\n" .
            "Cookie: foo=bar\r\n"
    ]
];

// Create the stream context
$context = stream_context_create($opts);
Copy after login

Once the stream context is created, you can pass it as the third argument to file_get_contents() to send the HTTP headers along with the request:

// Send the request with headers
$file = file_get_contents('http://www.example.com/', false, $context);
Copy after login

The above is the detailed content of How Can I Send HTTP Headers with PHP's file_get_contents()?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template