Search code examples
phpdrupaldrupal-7

Drupal 7.xx - how can I check for user auth and allow access to a custom web application running alongside Drupal?


I have a custom PHP web app that I have running in a folder off of the Drupal sites root.

What I'm hoping to do is ONLY allow access to this custom PHP web app -- /folder/mycoolapp.php -- when a user is logged into the Drupal site.

For now, what I have is a basic drupal 'page' that when accessed checks the

global $user; 

array for a specific access 'role', and I might also use the value

$user[login] => 1538264018

to check that the user is recently logged in as a means of restricting access to the web app.

I thought about just relying on the referrer (making sure it always matched a specific / single page on my server (a Drupal page) in order to allow access -- but I am pretty sure the referrer can be spoofed.

Question here is what can I do to have my custom web app (PHP) that I load via

header('Location: /path/to/mycoolapp.php');

only show for valid logged in users?

I tried accessing the $user object in the custom PHP page but no dice.

I tried exploring a way to refer to the SID to retrieve the current 'Session' but couldn't get that to work either.


Solution

  • I see 2 solutions here:

    1. To create custom drupal page and add your custom code to it, to generate page content. That way you would have to "embed" your app into drupal:

      /**

      • Implements hook_menu(). */ function modulename_menu() {

        $items['your/special/path'] = array( 'type' => MENU_NORMAL_ITEM, 'title' => t('Title'), 'description' => 'My custom and very special page', 'page callback' => 'modulename_special_page', 'access callback' => 'user_access', 'access arguments' => array('access content'), );

        return $items; }

      /**

      • Page callback. */ function modulename_special_page() { $content = 'Hello World'; // ... embed your custom code here; return $content; }

      Check out: https://drupal.stackexchange.com/questions/81539/add-custom-page

    2. To include drupal's bootstrap at beginning of your script and after that you can use drupal's system, check if user is logged in and similar. Something like:

      require_once './includes/bootstrap.inc'; // assuming your script is in the same folder as Drupal's index.php drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL); // you now have access to all Drupal functionality

    .. as explained in this article: https://www.drupal.org/forum/support/module-development-and-code-questions/2008-05-19/how-to-use-drupal-api-outside-of