Blocking certain users from accessing a given page in Drupal

(this information is now part of the How I Created this modeling portal with Drupal page)

I recently had to create a page only accessible for: Registered Users AND users with an id matching one of the values in a Table X (e.g. to make sure that users have signed up for a specific service before letting them access it). Here is how I did it.

For the first part, there are several Drupal modules (e.g. this one ) that can be used for this purpose. However, since I just had to block users from a small number of pages I decided it was not worth to install any additional module so I wrote the corresponding PHP code myself. For the second part, it is necessary to access the database using the functions provided by the Drupal database interface .

Btw, I’m NOT claiming this IS the best code you’ve ever seen! Hope at least it gives you a hint of how to handle this issue

// Accessing the predefined global variable $user
global $user; 

//Checking if the user is registered (i.e. has "authenticated user" as a role)
if (in_array('authenticated USER', $user->roles))
{
  //If so, we check a row for the user exists in the table X
  $result = db_query('SELECT x.id FROM mola_tableX x WHERE x.id=%s',$user->uid);
  $exists=db_fetch_object($result);
  if ($exists)
  {
     //Everything is right. Go on with the page loading
  }
  else {  //Dealing with the error   }
}
else{  //Dealing with the error }

If you enjoyed the post you can subscribe to this Software Modeling blog and/or follow me on twitter . And if you really liked it help me pass it on to others by bookmarking and sharing the post using the links below:

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Powered by WordPress
More in drupal
Accessing non-drupal folders within a drupal site
How did I create this site?
Close