JohnMi
JohnMi

Reputation: 81

Htaccess compare a cookie name with a value in the database

Is there any way that I can compare a cookie value to a string saved in the database in my htaccess . ? A string is a random key generated every time user logs in .

I want it to be like this

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

Please help , I have tried all over Google and SO with no lucky ,

Upvotes: 2

Views: 883

Answers (2)

MrWhite
MrWhite

Reputation: 45829

You can't perform a database lookup in .htaccess (using PHP) in order to get the value to check for. .htaccess finishes long before PHP gets a chance to do anything.

What you can do in .htaccess is internally rewrite all requests to your PHP script which does the necessary lookup, checks the cookie and processes it accordingly. Something like:

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

For example... if you request /somefile.php, the above directives will rewrite this request to /cookie-check.php. The browser still shows /somefile.php in the browser address bar (this is an internal rewrite, not an external redirect). Then, in "cookie-check.php" you do something like:

<?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"?
}

Upvotes: 1

adear11
adear11

Reputation: 945

You can't do that in an htaccess file. You'd have to redirect to a generic php page that checks the cookies value.

Upvotes: 0

Related Questions