How to access current logged in user information outside of Drupal

If you are writing PHP code in Drupal and would like to access basic user information (e.g. UID, username), you can simply define the global variable $user and get the data from there:

However, it would be more complicated when you want to access the same information outside of Drupal system (but still in the same domain). For instance, you want to implement a PHP page to provide data to your JavaScript (AJAX or Web API style), and you want to have access to the current Drupal user directly inside your PHP code instead of passing the UID around (which is quite insecure in my opinion).

My problem is briefly demonstrated in the diagram below:

Access Drupal user from the outside

Using the exact code above, you will just get an empty $user variable. It is quite expected considering your PHP code is completely outside of Drupal framework at the moment.

If you take note at the cookies sent to the outside PHP pages, you would find the same Session cookie sent to Drupal pages (SESS****), which basically mean that you should be able to access the current user information (and other session variables). All you have to do is to initialize the Drupal framework in your PHP pages.

If you do not see the Session cookie being sent, probably your PHP is in a different domain from your  Drupal site, or your $cookie_domain in sites/default/settings.php is set incorrectly. You can try comment the $cookie_domain line or set it to a proper value.

You can have a look at the 2 original pages that I learn these things from:

If you have a better way or have any questions, please leave a comment below.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.