What is the purpose of using the header() function in PHP?
The header() function in PHP is used to send raw HTTP headers to the client. This can be useful for various purposes such as redirecting the user to a different page, setting cookies, caching control, and more. It is commonly used to perform tasks that need to be done before any output is sent to the browser.
<?php
// Redirect the user to a different page after 5 seconds
header("Refresh: 5; url=redirect_page.php");
// Set a cookie with a value that expires in 24 hours
header("Set-Cookie: cookie_name=cookie_value; expires=" . gmdate('D, d M Y H:i:s \G\M\T', time() + 86400));
// Prevent caching of the current page
header("Cache-Control: no-cache, no-store, must-revalidate");
header("Pragma: no-cache");
header("Expires: 0");
?>
Related Questions
- What are the benefits of using a DOM parser over regular expressions for parsing HTML in PHP?
- What are some common pitfalls when using PHP forms for processing user input?
- What are the possible pitfalls of using PHP to extract hierarchical category data from MySQL tables for CSV export, and how can they be mitigated?