How can HTTP authentication be implemented for securing multiple pages in PHP?
To implement HTTP authentication for securing multiple pages in PHP, you can use the `$_SERVER['PHP_AUTH_USER']` and `$_SERVER['PHP_AUTH_PW']` variables to authenticate users. You can create a function that checks these variables against a predefined username and password, and if they match, allow access to the protected pages.
<?php
function authenticate() {
if(!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW']) || $_SERVER['PHP_AUTH_USER'] != 'username' || $_SERVER['PHP_AUTH_PW'] != 'password') {
header('WWW-Authenticate: Basic realm="Restricted Area"');
header('HTTP/1.0 401 Unauthorized');
echo 'Access Denied';
exit;
}
}
authenticate();
?>
Related Questions
- Which approach, Variant 1 or Variant 2, is more efficient for performance and reducing server load in a high-traffic project?
- What are the potential pitfalls of including a library multiple times in a PHP script?
- How can the data type of a variable affect the outcome of Modulo Division in PHP, as seen in the forum thread?