PHP如何实现给页面设置独立访问密码
To implement password protection for individual pages in PHP, you can follow these general steps:
page1:password1
page2:password2
<?php
// Check if password is required for this page
$page = $_GET['page']; // Get the requested page name
$passwordFile = 'passwords.txt'; // Path to the password file
if (file_exists($passwordFile)) {
$passwords = file($passwordFile); // Read password file into an array
if (isset($passwords[$page])) {
$requiredPassword = $passwords[$page]; // Get password for this page
if (!isset($_POST['password']) || $_POST['password'] !== $requiredPassword) {
// Password not provided or incorrect
header('HTTP/1.4 401 Unauthorized');
echo 'Access denied. Please enter the correct password.';
exit;
}
}
}
// Page content goes here
?>
// Password is correct, allow access to page content
?>
<!DOCTYPE html>
<html>
<head>
<title>Protected Page</title>
</head>
<body>
<h1>Protected Content</h1>
</body>
</html>
// Password is incorrect, display error message
?>
<!DOCTYPE html>
<html>
<head>
<title>Access Denied</title>
</head>
<body>
<h1>Access Denied</h1>
<p>Incorrect password. Please try again.</p>
<form action="" method="post">
<label for="password">Password:</label>
<input type="password" name="password" id="password" required>
<input type="submit" value="Login">
</form>
</body>
</html>
Remember to store password files securely and consider using more robust password hashing and storage mechanisms for production environments.