1

I am working on a site where on a page I am querying some data related to my project.

Here I have many clients and I have given all of them access to project search page. On search page I run a query according to the fields selected by the user and display the result as a table on the page itself. But my query is as such that it is not user dependent.

I just want to ensure that each user has a specific set of output for itself (i.e not all the table would be displayed to all users).

How do I get the username or user ID of the logged-in user?

1
  • You have access to the current user with the global variable global $user. So you can have $userlogin = $user->login;, $userID = $user->uid;, etc ...
    – Lovau
    Commented May 20, 2014 at 12:47

2 Answers 2

3

You can use the global $user object:

An object representing the user currently visiting the site.

Contains preferences and other account information for logged-in users. When a user is not logged-in, the $user->uid property is set to 0.

e.g.

global $user;
$name = $user->name;
$id = $user->uid;

// or
$name = $GLOBALS['user']->name;
$id = $GLOBALS['user']->uid;
2
  • Where should I write this piece of code in my website. Commented May 23, 2014 at 5:08
  • Wherever you need to use it....
    – Clive
    Commented May 23, 2014 at 7:21
0

You can use:

   global $user;      
   if (!empty($user->uid))
   {$id = $user->uid;} //$id will only have a value if user is logged in
3
  • When a user is not logged-in, the $user->uid property is set to 0. ...if you're looking to test whether or not the user is actually logged in user_is_logged_in() and user_is_anonymous() would probably be more appropriate
    – Clive
    Commented May 20, 2014 at 13:09
  • 0 will return empty() to be TRUE so $id will not be set! Commented May 20, 2014 at 13:11
  • Yeah sorry, hadn't finished writing that comment when I submitted it :)
    – Clive
    Commented May 20, 2014 at 13:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.