<?php
$password = "1234"; // 修改為您的密碼
$p = ""; // 錯誤提示變量
$isview = false;
// 1. 檢查 Cookie 自動驗證
if (isset($_COOKIE["isview"]) && $_COOKIE["isview"] === $password) {
$isview = true;
} else {
// 2. 處理表單提交
if (isset($_POST["pwd"])) {
if ($_POST["pwd"] === $password) {
// 密碼正確:設置 Cookie (3小時)
setcookie("isview", $_POST["pwd"], time() + 3600 * 3);
$isview = true;
} else {
$p = empty($_POST["pwd"])
? "需要密碼才能查看,請輸入密碼。"
: "密碼不正確,請重新輸入。";
}
} else {
// 3. 首次訪問無提交
$p = "請輸入密碼查看,獲取密碼可聯系我。";
}
}
// 4. 輸出內容
if ($isview) {
?>
<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>受保護內容</title></head><body>
<h1>🔓 驗證通過,歡迎查看受保護內容</h1>
<p>這裡放置您的機密內容、下載鏈接、內部文檔等...</p>
</body></html>
<?php
} else {
?>
<!DOCTYPE html>
<html><head>
<meta charset="utf-8">
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<title>請輸入密碼</title>
<style>
body { margin:0; padding:0; background:#f5f5f5; font-family: "Microsoft YaHei", sans-serif; }
.passport {
width: 380px; padding: 30px; background: #fff; border-radius: 8px;
box-shadow: 0 4px 20px rgba(0,0,0,.1);
position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%);
text-align: center; border-top: 4px solid #e74c3c;
}
.passport h3 { margin: 0 0 20px; color: #333; font-size: 18px; }
.passport input[type="password"] {
width: 70%; padding: 12px; border: 1px solid #ddd; border-radius: 4px;
font-size: 16px; margin-right: 8px;
}
.passport input[type="submit"] {
padding: 12px 28px; background: #e74c3c; color: #fff; border: none;
border-radius: 4px; cursor: pointer; font-size: 16px; transition: .3s;
}
.passport input[type="submit"]:hover { background: #c0392b; }
.msg { margin-top: 15px; color: #e74c3c; font-size: 14px; }
</style>
</head><body>
<div class="passport">
<h3>🔒 內容加密保護</h3>
<form method="post">
<input type="password" name="pwd" placeholder="請輸入訪問密碼" autocomplete="off" required>
<input type="submit" value="驗證並查看">
</form>
<?php if ($p): ?><div class="msg"><?php echo $p; ?></div><?php endif; ?>
</div>
</body></html>
<?php
}
| 階段 | 代碼片段 | 說明 |
|---|---|---|
| Cookie 檢查 | $_COOKIE["isview"] === $password | 嚴格比較,防止類型轉換繞過 |
| 表單處理 | isset($_POST["pwd"]) | 區分首次訪問與提交驗證 |
| 錯誤提示 | 三元運算符區分空/錯誤 | 用戶體驗細節優化 |
| Cookie 設置 | setcookie(..., time()+10800) | 3小時有效期,可配置化 |
| 防緩存 | Meta 標簽 + no-cache | 防止瀏覽器緩存導致狀態異常 |
setcookie(..., '', ..., true, true) (Secure + HttpOnly)代碼簡潔易改,將 $password 改為環境變量/配置文件讀取,即可投入實際使用。