Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's PHP Equivalent of Java Servlet Filter?

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.

like image 535
ZZ Coder Avatar asked Oct 02 '09 00:10

ZZ Coder


Video Answer


2 Answers

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
}
like image 149
cletus Avatar answered Sep 17 '22 15:09

cletus


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.

like image 25
Sabeen Malik Avatar answered Sep 18 '22 15:09

Sabeen Malik