Htaccess 将 cookie 名称与数据库中的值进行比较

Htaccess compare a cookie name with a value in the database

有什么方法可以将 cookie 值与保存在我的 htaccess 数据库中的字符串进行比较。 ?字符串是用户每次登录时生成的随机密钥。

我想要这样

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_COOKIE} !CookieName=Some-Cookie-Value-Script.php [NC] 
RewriteRule .* http://www.example.com/login.php [L]

// How do I check if CookieName value is equally to the one in the database 
// returned by Some-Cookie-Value-Script.php

请帮忙,我已经试遍了 Google 和 SO 都没有运气,

您不能在 htaccess 文件中这样做。您必须重定向到检查 cookie 值的通用 php 页面。

您不能在 .htaccess 中执行数据库查找(使用 PHP)以获得要检查的值。 .htaccess 在 PHP 有机会做任何事情之前很久就完成了。

您可以在 .htaccess 中做的是在内部将所有请求重写到您的 PHP 脚本,该脚本执行必要的查找、检查 cookie 并相应地处理它。类似于:

RewriteEngine On
RewriteCond %{REQUEST_URI} !^/cookie-check\.php
RewriteRule .* /cookie-check.php [L]

例如...如果您请求 /somefile.php,上述指令会将此请求重写为 /cookie-check.php。浏览器仍然在浏览器地址栏中显示 /somefile.php(这是 内部重写 ,而不是 外部重定向 )。然后,在 "cookie-check.php" 你做这样的事情:

<?php
$cookie = isset($_COOKIE['cookiename']) ? $_COOKIE['cookiename'] : null;
if ($cookie) {
    // The cookie is set, check that it is the expected value...
    // Perform database lookup to get expected cookie value
    $expectedCookie = '<value looked up from DB>';
    if ($cookie == $expectedCookie) {
        // The cookie is set and it is the expected value
        // Check $_SERVER['REQUEST_URI'] for the requested URL and load
        // the page as normal
        // ...

    } else {
        // The cookie exists but it is not the expected value
        // Redirect to "login.php"?
    }
} else {
    // The cookie does not exist at all
    // Redirect to "login.php"?
}