Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking Drupal authentication from external PHP

This may well be simple, but I'm new to Drupal. The organization I work for switched to Drupal a little while ago, but there's still some legacy code in various external PHP files that would be cumbersome to convert over to work within Drupal.

However, it would be very nice to be able to restrict access to some of these pages based on a person being authenticated against Drupal. (Some pages are administrative and are currently visible to anyone who knows the URL, for instance. Yes, poor design, but that's what I inherited...)

How can I check with Drupal, from an external PHP file, to see if the person visiting a given page has authenticated?

like image 979
mjjohnson Avatar asked Dec 29 '22 22:12

mjjohnson


2 Answers

I would go with Rimians suggestion of registering the URLs within Drupal itself (+1), but as an alternative, you can bootstrap Drupal 'manually' and check a user permission after that directly from other scripts as well:

// initialize Drupal
// TODO: adjust path according to placement of script (might need to change to Drupal directory first)
require './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
// check user access rights
// TODO: Adjust to the permission you want to restrict to, e.g. 'access content' or whatever
if (!user_access('administer nodes')) {
  // Insufficient rights, say so
  drupal_access_denied();
  exit(0);
}
// ... call legacy script

NOTE: Drupal does quite a bit of work during bootstrap, including some manipulation and setting of global variables, so make sure to check carefully for interferences/clashes with the legacy code (would also apply for Rimians suggestion).

If you want to restrict access to authenticated users only, you can replace the user_access() call with user_is_logged_in(). If you want to check by role, you can add a global $user; and check the contents of the $user->roles array

like image 117
Henrik Opel Avatar answered Dec 31 '22 15:12

Henrik Opel


You'd need to include those URLs in the menu router so Drupal can bootstrap and check your permissions. Then you'd need to find away to run your third party PHP as an include file or maybe through an interface.

Some clever custom work is required but possibly not too hard. :)

like image 30
Rimian Avatar answered Dec 31 '22 14:12

Rimian