This repository has been archived on 2025-01-19. You can view files and clone it, but cannot push or open issues or pull requests.
oliverdavies.uk-old-sculpin/source/_posts/checking-if-user-logged-drupal-right-way.md

58 lines
1.5 KiB
Markdown
Raw Normal View History

2015-03-16 11:22:24 +00:00
---
title: Checking if a user is logged into Drupal (the right way)
2020-03-08 14:32:13 +00:00
date: 2013-01-09
2018-12-31 12:13:05 +00:00
excerpt: How to check if a user is logged in by using Drupal core API functions.
2015-03-16 11:22:24 +00:00
tags:
2015-06-14 02:27:41 +00:00
- drupal
- drupal-6
- drupal-7
- drupal-planet
- php
2015-03-16 11:22:24 +00:00
---
2015-06-18 07:58:56 +00:00
I see this regularly when working on Drupal sites when someone wants to check whether the current user is logged in to Drupal (authenticated) or not (anonymous).
2017-03-16 08:09:52 +00:00
```language-php
2015-03-16 11:22:24 +00:00
global $user;
if ($user->uid) {
2015-06-14 02:27:41 +00:00
// The user is logged in.
2015-03-16 11:22:24 +00:00
}
2017-03-16 08:09:52 +00:00
```
2015-03-16 11:22:24 +00:00
or
2017-03-16 08:09:52 +00:00
```language-php
2015-03-16 11:22:24 +00:00
global $user;
if (!$user->uid) {
2015-06-14 02:27:41 +00:00
// The user is not logged in.
2015-03-16 11:22:24 +00:00
}
2017-03-16 08:09:52 +00:00
```
2015-03-16 11:22:24 +00:00
The better way to do this is to use the [user_is_logged_in()](http://api.drupal.org/api/drupal/modules!user!user.module/function/user_is_logged_in/7) function.
2017-03-16 08:09:52 +00:00
```language-php
2015-03-16 11:22:24 +00:00
if (user_is_logged_in()) {
2015-06-14 02:27:41 +00:00
// Do something.
2015-03-16 11:22:24 +00:00
}
2017-03-16 08:09:52 +00:00
```
2015-03-16 11:22:24 +00:00
This returns a boolean (TRUE or FALSE) depending or not the user is logged in. Essentially, it does the same thing as the first example, but there's no need to load the global variable.
A great use case for this is within a `hook_menu()` implementation within a custom module.
2017-03-16 08:09:52 +00:00
```language-php
2015-03-16 11:22:24 +00:00
/**
* Implements hook_menu().
*/
function mymodule_menu() {
2015-06-14 02:27:41 +00:00
$items['foo'] = array(
'title' => 'Foo',
'page callback' => 'mymodule_foo',
'access callback' => 'user_is_logged_in',
);
2015-03-16 11:22:24 +00:00
2015-06-14 02:27:41 +00:00
return $items;
2015-03-16 11:22:24 +00:00
}
2017-03-16 08:09:52 +00:00
```
2015-03-16 11:22:24 +00:00
2015-06-14 02:27:41 +00:00
There is also a [user_is_anonymous()](http://api.drupal.org/api/drupal/modules!user!user.module/function/user_is_anonymous/7) function if you want the opposite result. Both of these functions are available in Drupal 6 and higher.