Current Location: Home> Latest Articles> Use header() + file_get_contents() to implement file forwarding

Use header() + file_get_contents() to implement file forwarding

M66 2025-05-28

In PHP, the header() function is used to send raw HTTP header information. If you want to redirect the user's request to another page, you can use the Location HTTP header. The basic syntax is as follows:

 header("Location: http://m66.net/your-target-page.php");
exit();

The above code will redirect the user from the current page to http://m66.net/your-target-page.php . The exit() function is used to ensure that the script stops executing after sending the header and no more outputs.

2. Use file_get_contents() to get file contents

file_get_contents() is a very common function in PHP, which is used to read the content of a file or URL. By using this function, you can get the contents of a remote file or local file.

 $content = file_get_contents("http://m66.net/some-file.php");

This line of code will read the contents of the http://m66.net/some-file.php file and store it in the $content variable.

3. Combining header() and file_get_contents() to implement file forwarding

You can combine the file_get_contents() and header() functions, first read the contents of the remote file, and then pass the contents to the user. This is an implementation method of file forwarding. The basic idea is to obtain file contents through file_get_contents() and send appropriate HTTP headers through header() to forward file contents.

 // Get the file content
$content = file_get_contents("http://m66.net/some-file.php");

// Set appropriately Content-Type head,Inform the browser of the type of content
header("Content-Type: text/html");

// Output file content
echo $content;
exit();

4. Implement simple file forwarding function

We can encapsulate this method into a function for more convenient use. The following is a simple file forwarding function implementation: