Use a web-application-framework.. like Drupal. Then put this at the top:
// 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
FYI: IT changes with each version. Then only allow profiles, or users based on their profile name or userid in that system, or as above, the individual permission.
https://stackoverflow.com/questions/2496348/checking-drupal-authentication-from-external-php/2499464#2499464
Then use the authentication modules, interactions, protections etc, already built into that.
Takes care of all the heavy lifting and updates to the API.
There are loads: Symfony, Magento, Zend... GIYF..