给PHP页面设置访问密码,PHP页面怎么设置页面访问密码
PHP

给PHP页面设置访问密码,PHP页面怎么设置页面访问密码

William
2026-01-27 / 0 评论 / 45 阅读 / 正在检测是否收录...

为你的页面支持加密访问无论什么程序只要是PHP程序都是支持这代码的,来实现加密访问你的加密页面或文章等等的页面,不保证其他程序可以正常使用麻烦先测试!

密码正确才能进去页面,进入后会存下cookies值,下一次登录的时候则不需要再次输入了。

如果不想给人看了,只需要更改密码,cookies就会立即失效,必须要重新登陆才能看。

效果

安装方法:

1、新建PHP文件,命名为:mima.php,把下面代码放进这个新建为PHP文件里面

<?php

/**
 * 使用说明:
 * 1. 将本脚本保存为 PageEncrypt.php。
 * 2. 在您想要加密的PHP页面开头包含这个文件:
 * require_once('PageEncrypt.php');
 * 3. 设置页面访问密码:
 * PageEncrypt('页面密码');
 */
 
// 定义密码Cookie加密盐,若未定义则设置默认值
if (!defined('MK_ENCRYPT_SALT')) {
    define('MK_ENCRYPT_SALT', 'Kgs$JC!V');
}
 
/**
 * 设置页面访问密码
 * @param string $password 访问密码
 * @param string $pageid 页面唯一ID,用于区分同一网站的不同加密页面,默认为'default'
 */
function PageEncrypt($password, $pageid = 'default') {
    // 生成页面ID并进行MD5加密
    $pageid = md5($pageid);
    
    // 对密码进行双重MD5加密,并附加盐值
    $md5pw = md5(md5($password) . MK_ENCRYPT_SALT);
    
    // 获取POST提交的密码,若不存在则设为空字符串
    $postpwd = filter_input(INPUT_POST, 'pagepwd', FILTER_SANITIZE_STRING);
    
    // 获取Cookie中保存的密码,若不存在则设为空字符串
    $cookieName = 'mk_encrypt_' . $pageid;
    $cookiepwd = filter_input(INPUT_COOKIE, $cookieName, FILTER_SANITIZE_STRING);
 
    // 如果Cookie中的密码匹配,则直接返回
    if (hash_equals($md5pw, $cookiepwd)) {
        return;
    }
    
    // 如果提交的密码正确,则设置Cookie并返回
    if (hash_equals($md5pw, md5(md5($postpwd) . MK_ENCRYPT_SALT))) {
        setcookie($cookieName, $md5pw, time() + 3600000, '/');
        return;
    }
    
    // 密码验证失败,显示密码输入页面
    header('Content-Type: text/html; charset=UTF-8');
    ?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>该页面已被加密</title>
    <style type="text/css">
*{font-family:"Microsoft Yahei",微软雅黑,"Helvetica Neue",Helvetica,"Hiragino Sans GB","WenQuanYi Micro Hei",sans-serif;box-sizing:border-box;margin:0px;padding:0px;font-size:14px;-webkit-transition:.2s;-moz-transition:.2s;-ms-transition:.2s;-o-transition:.2s;transition:.2s}
html,body{width:100%;height:100%}
body{background-color:#F4F6F9;color:#768093}
input,button{font-size:1em;border-radius:3px;-webkit-appearance:none}
input{width:100%;padding:5px;box-sizing:border-box;border:1px solid #e5e9ef;background-color:#f4f5f7;resize:vertical}
input:focus{background-color:#fff;outline:none}
button{border:0;background:#6abd09;color:#fff;cursor:pointer;opacity:1;user-select:none}
button:hover,button:focus{opacity:.9}
button:active{opacity:1}
.main{width:100%;max-width:500px;height:300px;padding:30px;background-color:#fff;border-radius:2px;box-shadow:0 10px 60px 0 rgba(29,29,31,0.09);transition:all .12s ease-out;position:absolute;left:0;top:0;bottom:0;right:0;margin:auto;text-align:center}
.alert{width:80px}
.mk-side-form{margin-bottom:28px}
.mk-side-form input{float:left;padding:2px 10px;width:77%;height:37px;border:1px solid #ebebeb;border-right-color:transparent;border-radius:2px 0 0 2px;line-height:37px}
.mk-side-form button{position:relative;overflow:visible;width:23%;height:37px;border-radius:0 2px 2px 0;text-transform:uppercase}
.pw-tip{font-weight:normal;font-size:26px;text-align:center;margin:25px auto}
#pw-error {color: red;margin-top: 15px;margin-bottom: -20px;}
.return-home{text-decoration:none;color:#b1b1b1;font-size:16px}
.return-home:hover{color:#1E9FFF;letter-spacing:5px}
</style>
</head>
<body>
<div class="main">
    <svg class="alert" viewBox="0 0 1084 1024" xmlns="http://www.w3.org/2000/svg" width="80" height="80">
<defs><style/></defs>
<path d="M1060.744 895.036L590.547 80.656a55.959 55.959 0 0 0-96.919 0L22.588 896.662a55.959 55.959 0 0 0 48.43 83.907h942.14a55.959 55.959 0 0 0 47.525-85.534zm-470.619-85.172a48.008 48.008 0 1 1-96.015 0v-1.567a48.008 48.008 0 1 1 96.015 0v1.567zm0-175.345a48.008 48.008 0 1 1-96.015 0V379.362a48.008 48.008 0 1 1 96.015 0v255.157z" fill="#FF9800"/>
</svg>
    <form action="" method="post" class="mk-side-form">
        <h2>该页面已被加密</h2>
        <input type="password" name="pagepwd" placeholder="请输入访问密码查看" required>
        <button type="submit">提交</button>
        <?php if ($postpwd): ?>
        <p id="pw-error">哎哟!密码不对哦~</p>
        <script>setTimeout(function() {document.getElementById('pw-error').style.display = 'none';}, 2000);</script>
        <?php endif; ?>
    </form>
    <a href="/" class="return-home">- 返回首页 -</a>
</div>
</body>
</html>
    <?php
    exit();
}
?>

2、把下面的代码放进你要加密的PHP页面里面,比如你要给首页:index.php 加密,就把下面代码放在index.php 的最前面

<?php
require_once('PageEncrypt.php');
PageEncrypt('1234');//这个就是密码
?>

20260127:

Update: 重构页面加密脚本至 Ultimate 版本

Security: 替换 MD5 为 HMAC-SHA256;增加 Cookie HttpOnly/Secure 属性;新增防暴力破解锁定机制(5次/15分钟)。

Feat: 新增注销功能 (?action=logout);支持 Config 数组动态配置;解决表单重复提交问题。

UI: 全新 Glassmorphism 毛玻璃风格界面,增加动态背景与交互动画,优化移动端显示。

Fix: 修复 PHP 8.1+ FILTER_SANITIZE_STRING 弃用警告。

<?php
/**
 * PageEncrypt Ultimate - 全功能单页加密脚本
 * 集成功能:防暴力破解、自动注销、动态配置、HMAC加密
 * * 使用方法: 
 * require_once('PageEncrypt.php');
 * PageEncrypt('你的密码', [
 * 'page_id' => 'my_private_page',
 * 'title'   => '内部数据',
 * ]);
 */

// 默认加密盐 (建议在引用此文件前定义该常量,或者直接修改此处)
if (!defined('MK_ENCRYPT_SALT')) {
    define('MK_ENCRYPT_SALT', 'Change_This_To_Something_Random_&_Complex_999');
}

/**
 * 核心加密函数
 * @param string $password 访问密码
 * @param array  $options  配置数组
 */
function PageEncrypt($password, $options = []) {
    // 1. 初始化配置
    $defaults = [
        'page_id'      => 'default',         // 页面ID,用于区分不同页面
        'title'        => '访问受限',         // 页面标题
        'cookie_time'  => 86400 * 7,         // Cookie有效期 (默认7天)
        'max_attempts' => 5,                 // 最大尝试次数
        'lockout_time' => 900,               // 锁定时间 (秒),默认15分钟
        'logout_param' => 'logout'           // 触发退出的URL参数名 (?action=logout)
    ];
    $config = array_merge($defaults, $options);
    
    // 生成唯一标识
    $pageIdHash = md5($config['page_id']);
    $cookieName = 'mk_encrypt_' . $pageIdHash;
    $sessionKey = 'mk_encrypt_limit_' . $pageIdHash;

    // 开启 Session (用于防爆破)
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }

    // 计算正确密码的哈希 (HMAC-SHA256)
    $correctHash = hash_hmac('sha256', $password, MK_ENCRYPT_SALT);

    // 2. 处理退出登录逻辑
    // 访问方式: yourpage.php?action=logout
    if (isset($_GET['action']) && $_GET['action'] === $config['logout_param']) {
        setcookie($cookieName, '', time() - 3600, '/'); // 清除Cookie
        // 清除URL参数并跳转回原页面
        $cleanUrl = strtok($_SERVER["REQUEST_URI"], '?');
        header("Location: " . $cleanUrl);
        exit();
    }

    // 3. 检查防暴力破解限制
    $attempts = $_SESSION[$sessionKey]['count'] ?? 0;
    $lastTime = $_SESSION[$sessionKey]['time'] ?? 0;
    $isLocked = false;

    if ($attempts >= $config['max_attempts']) {
        if (time() - $lastTime < $config['lockout_time']) {
            $isLocked = true;
            $remainingTime = ceil(($config['lockout_time'] - (time() - $lastTime)) / 60);
            $errorMsg = "尝试次数过多,请 {$remainingTime} 分钟后再试。";
        } else {
            // 锁定时间已过,重置计数
            unset($_SESSION[$sessionKey]);
            $attempts = 0;
        }
    }

    // 4. 验证 Cookie (如果未锁定)
    if (!$isLocked) {
        $cookiePwd = $_COOKIE[$cookieName] ?? '';
        if (!empty($cookiePwd) && hash_equals($correctHash, $cookiePwd)) {
            // 验证通过,重置错误计数并返回
            unset($_SESSION[$sessionKey]);
            return; 
        }
    }

    // 5. 处理 POST 提交 (如果未锁定)
    if (!$isLocked && $_SERVER['REQUEST_METHOD'] === 'POST') {
        $inputPwd = $_POST['pagepwd'] ?? '';
        
        // 验证密码
        if (hash_equals($correctHash, hash_hmac('sha256', $inputPwd, MK_ENCRYPT_SALT))) {
            // 密码正确
            setcookie($cookieName, $correctHash, [
                'expires'  => time() + $config['cookie_time'],
                'path'     => '/',
                'secure'   => isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on',
                'httponly' => true,
                'samesite' => 'Strict'
            ]);
            
            // 登录成功,清空错误计数
            unset($_SESSION[$sessionKey]);

            // 刷新页面
            header("Location: " . strtok($_SERVER["REQUEST_URI"], '?'));
            exit();
        } else {
            // 密码错误:记录次数
            $_SESSION[$sessionKey] = [
                'count' => $attempts + 1,
                'time'  => time()
            ];
            $errorMsg = "密码错误!剩余尝试次数: " . ($config['max_attempts'] - ($attempts + 1));
            
            // 如果刚才是最后一次尝试,立即显示锁定
            if (($attempts + 1) >= $config['max_attempts']) {
                $errorMsg = "尝试次数过多,已被锁定。";
                $isLocked = true;
            }
        }
    }

    // 6. 渲染登录界面
    // 如果执行到这里,说明没有通过验证,显示登录框并终止脚本
    renderLoginForm($config['title'], $errorMsg ?? null, $isLocked);
    exit();
}

/**
 * 渲染 HTML 界面 (Modern Glass UI)
 */
function renderLoginForm($title, $errorMsg, $isLocked) {
    header('Content-Type: text/html; charset=UTF-8');
    ?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title><?php echo htmlspecialchars($title); ?></title>
    <style>
        :root {
            --glass-bg: rgba(255, 255, 255, 0.75);
            --glass-border: rgba(255, 255, 255, 0.6);
            --primary-color: #4f46e5;
            --primary-hover: #4338ca;
            --text-main: #1f2937;
            --text-sub: #6b7280;
            --error-bg: #fee2e2;
            --error-text: #ef4444;
        }

        * { margin: 0; padding: 0; box-sizing: border-box; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; }
        
        body {
            height: 100vh;
            width: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            /* 动态渐变背景 */
            background: linear-gradient(-45deg, #ee7752, #e73c7e, #23a6d5, #23d5ab);
            background-size: 400% 400%;
            animation: gradientBG 15s ease infinite;
            overflow: hidden;
        }

        @keyframes gradientBG {
            0% { background-position: 0% 50%; }
            50% { background-position: 100% 50%; }
            100% { background-position: 0% 50%; }
        }

        .container {
            position: relative;
            width: 100%;
            max-width: 420px;
            padding: 20px;
        }

        .glass-card {
            background: var(--glass-bg);
            backdrop-filter: blur(16px);
            -webkit-backdrop-filter: blur(16px);
            border: 1px solid var(--glass-border);
            border-radius: 24px;
            padding: 40px 32px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
            text-align: center;
            transition: transform 0.3s ease;
        }

        .icon-wrapper {
            width: 64px;
            height: 64px;
            background: rgba(79, 70, 229, 0.1);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 20px;
        }

        .icon-wrapper svg {
            width: 32px;
            height: 32px;
            color: var(--primary-color);
        }

        h1 {
            font-size: 24px;
            font-weight: 700;
            color: var(--text-main);
            margin-bottom: 8px;
            letter-spacing: -0.5px;
        }

        p.subtitle {
            font-size: 14px;
            color: var(--text-sub);
            margin-bottom: 32px;
        }

        .input-group {
            position: relative;
            margin-bottom: 20px;
        }

        input {
            width: 100%;
            padding: 14px 16px;
            padding-left: 44px;
            border: 2px solid transparent;
            background: rgba(255, 255, 255, 0.6);
            border-radius: 12px;
            font-size: 16px;
            color: var(--text-main);
            transition: all 0.3s ease;
            outline: none;
        }

        input:focus {
            background: #fff;
            border-color: var(--primary-color);
            box-shadow: 0 0 0 4px rgba(79, 70, 229, 0.1);
        }

        input:disabled {
            background: #e5e7eb;
            cursor: not-allowed;
        }

        .input-icon {
            position: absolute;
            left: 14px;
            top: 50%;
            transform: translateY(-50%);
            color: #9ca3af;
            width: 20px;
            height: 20px;
        }

        input:focus + .input-icon {
            color: var(--primary-color);
        }

        button {
            width: 100%;
            padding: 14px;
            background: var(--primary-color);
            color: white;
            border: none;
            border-radius: 12px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s ease;
            box-shadow: 0 4px 6px -1px rgba(79, 70, 229, 0.2);
        }

        button:hover:not(:disabled) {
            background: var(--primary-hover);
            transform: translateY(-1px);
            box-shadow: 0 6px 8px -1px rgba(79, 70, 229, 0.3);
        }

        button:active:not(:disabled) {
            transform: translateY(0);
        }

        button:disabled {
            background: #9ca3af;
            cursor: not-allowed;
            opacity: 0.8;
            box-shadow: none;
        }

        .error-message {
            margin-top: 16px;
            padding: 10px;
            background: var(--error-bg);
            color: var(--error-text);
            font-size: 14px;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 6px;
            animation: shake 0.5s cubic-bezier(.36,.07,.19,.97) both;
        }

        .footer {
            margin-top: 24px;
            font-size: 13px;
        }

        .footer a {
            color: var(--text-sub);
            text-decoration: none;
            transition: color 0.2s;
        }

        .footer a:hover {
            color: var(--primary-color);
            text-decoration: underline;
        }

        @keyframes shake {
            10%, 90% { transform: translate3d(-1px, 0, 0); }
            20%, 80% { transform: translate3d(2px, 0, 0); }
            30%, 50%, 70% { transform: translate3d(-4px, 0, 0); }
            40%, 60% { transform: translate3d(4px, 0, 0); }
        }

        /* 移动端优化 */
        @media (max-width: 480px) {
            .glass-card { padding: 32px 24px; }
            h1 { font-size: 22px; }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="glass-card">
            <div class="icon-wrapper">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                    <rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect>
                    <path d="M7 11V7a5 5 0 0 1 10 0v4"></path>
                </svg>
            </div>

            <h1><?php echo htmlspecialchars($title); ?></h1>
            <p class="subtitle">此页面内容受密码保护</p>

            <form method="post">
                <div class="input-group">
                    <input type="password" name="pagepwd" placeholder="请输入访问密码" 
                           <?php echo $isLocked ? 'disabled' : 'autofocus'; ?> required autocomplete="current-password">
                    <svg class="input-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                        <path d="M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"></path>
                    </svg>
                </div>

                <button type="submit" <?php echo $isLocked ? 'disabled' : ''; ?>>
                    <?php echo $isLocked ? '暂时锁定' : '立即查看'; ?>
                </button>

                <?php if ($errorMsg): ?>
                    <div class="error-message">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                            <circle cx="12" cy="12" r="10"></circle>
                            <line x1="12" y1="8" x2="12" y2="12"></line>
                            <line x1="12" y1="16" x2="12.01" y2="16"></line>
                        </svg>
                        <span><?php echo htmlspecialchars($errorMsg); ?></span>
                    </div>
                <?php endif; ?>
            </form>

            <div class="footer">
                <a href="/">← 返回首页</a>
            </div>
        </div>
    </div>
</body>
</html>
    <?php
}
?>

Ultimate版本基础用法跟原来一样,只需要一行密码即可,其他使用默认配置。

<?php
require_once('PageEncrypt.php');
PageEncrypt('mypassword123'); // 默认配置:5次机会,锁定15分钟
?>
<h1>欢迎访问加密页面</h1>

高级用法:自定义标题和限制

如果你想修改标题,或者让密码试错机会更多/更少。

<?php
require_once('PageEncrypt.php');

PageEncrypt('super_secret_pw', [
    'page_id'      => 'admin_dashboard', // 必须设置,用于区分 Session
    'title'        => '管理员后台 - 请登录',
    'max_attempts' => 3,                 // 只能错3次
    'lockout_time' => 300,               // 锁定 5 分钟 (300秒)
    'cookie_time'  => 3600               // 登录有效期 1 小时
]);
?>

如何添加“退出登录”按钮

在你的加密页面内容中,添加一个链接即可:

<h1>内部资料</h1>
<p>这里是机密内容...</p>
<a href="?action=logout" style="color: red;">[退出登录]</a>
0

评论 (0)

取消