How to check if user is logged without bootstrapping - using .htaccess file

Tue, 2011-09-20 09:59

In this post, I'm going to say you how to check if the remote user is logged in to your Drupal network. There's no need to bootstrap Drupal at all. The point is, we are checking the client's cookie storage to see if Drupal's logged in cookies are set.

This small trick will help forbidding access to files for anonymous users from your host. For an example, say you are giving away a GPL theme to all registered users, you can easily wrap access to the "giving away node" but not to file itself. Others can get your direct download URL and distribute it as they want. Don't say me that it's GPL, remember - it's our bandwidth ;)

There's an exception though. You can put this .htaccess trick anywhere you want but Drupal'd cookie must be there. If your site is hosted on, you can make use of this trick from , , , etc. But not from

Let's start.

Create a .htaccess file in the root of the directory, and add the following code to it.

<IfModule mod_rewrite.c>
   RewriteEngine on
   RewriteCond %{HTTP_COOKIE} !DRUPAL_UID=1
   RewriteRule .* [R]

This will check if the client who access the file has DRUPAL_UID cookie set. If Please note that advanced users can manually set a cookie named DRUPAL_UID and add some number (>= 1) to download the file without actually logging in. So this is not a better way to deny access for files you sale. But the reason why you don't have to worry to much is nobody except you know that .htaccess file is checking the cookie.

This stupid piece of shi**y code will prevent some download managers (that don't have browser integration)

If this doesn't work, make sure that $cookie_domain thing in settings.php setup like - note the "dot" before .