In some future PHP far far away
... we will have Apache hooks

In your httpd.conf
phpAuthHandler = /path/to/your/auth_code.php
<?php
// ... logic ...
return OK;
?>
Other handlers
phpUriHandler
phpAccessHandler
phpHeaderHandler
phpTypeHandler
phpFixupHandler
phpLoggerHandler
phpPostReadHandler
phpResponseHandler