views:

334

answers:

3

On Java side, we have a servlet filter that handles authentication. We don't have to change all other servlet or JSPs to add authentication to the page, unless the page needs customized content.

How can we achieve the same on PHP? We don't use any frameworks on PHP.

+1  A: 

if i understand your question correctly.This can vary on architecture .. for instance .. create an include file which checks if the user is authenticated via the session , if not send to a login page. i think any site with more than 2 scripts would utilize some sort of include file and u can put this code in that file. you can even have an array which contains the names of the pages which need to have a valid user session and match that with request uri .. several ways to go about it .. u just need to choose the one which suits u most.

Sabeen Malik
+3  A: 

There is no directly equivalent. Your best bet is to include a common file at the top and do such logic at the top of that as required. So:

require 'common.php';

with:

if (!isset($_SESSION['userid'])) {
  // authentication stuff
}

If you want to do something at the end you have a couple of options:

  1. Use an output buffer handler with ob_start(); or
  2. Register a shutdown callback with register_shutdown_function().

So:

ob_start('my_callback');

function my_callback($str) {
  // do something
  return $str;
}

or

register_shutdown_function(my_callback);

function my_callback() {
  // do something
}
cletus
A: 

auto_prepend_file in php.ini. I dunno if this might help. But it worth for you to take a look into.

j2p