How can the header() function in PHP be utilized to control caching behavior and prevent unauthorized access to pages?
To control caching behavior and prevent unauthorized access to pages in PHP, you can use the header() function to send HTTP headers to the browser. By setting appropriate cache-control headers, you can control how the browser caches the page content. Additionally, by setting headers to check for authorization credentials, you can restrict access to certain pages.
<?php
// Prevent caching of the page
header("Cache-Control: no-cache, no-store, must-revalidate");
header("Pragma: no-cache");
header("Expires: 0");
// Check for authorization credentials
if(!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
header("HTTP/1.1 401 Unauthorized");
exit();
}
?>