views:

81

answers:

5

This is maybe a stupid question, but I figured I'd ask before I did something goofy: I've got an web application with a custom Login dialog which takes a user/pass that gets sent to the server. If both match an entry in the database, then there is maybe 10 or so pages that the user gets access to (depending on the rights associated with that account)...pretty straight forward for the most part.

Of course, if the user attempts to access one of these pages without having actually logged in, or has insufficient privileges, then I'm required to bounce him or back to the Login page to type in a user name/password that would give them access.

My Question: It would seem that for me to do this, I am required to put a call at the top of each restricted PHP page which checks the credentials and redirects if they are missing or insufficient...Is this a sound approach? Or does PHP offer a more intelligent way which does not requires the call be duplicated in near-all pages of the application?

BTW: This is not an MVC app - Just straight PHP

Thanks!

+6  A: 

Yeah; you'll need to check on every page if this is simple PHP. This doesn't need to be difficult though:

if (!hasAccess($user, $page))
{
  header("Location: signin.php?redirecturl={$page}");
  die();
}

And do your logic within hasAccess(). You can even include this logic within a separate file, and include it on all of your pages, keeping the code itself in one place in case you wish to make future updates to the criteria for access, or anything else.

Jonathan Sampson
I'd `urlencode()` the `$page` too, just to be safe.
Mark
`$page` isn't necessarily a path. Could be an integer :)
Jonathan Sampson
Thanks much - That answers my question. Glad to know I'm sane.
Robert
Robert, I never said you were sane :) Perhaps we're both crazy!
Jonathan Sampson
Do you mind if I make a small addition? This solution is insecure if it is going to be included at the top of each page. A hacker could simply ignore the Location header and view the rest of the page.
Sam152
+2  A: 

Start with this tutorial: http://www.phpro.org/tutorials/Basic-Login-Authentication-with-PHP-and-MySQL.html

mmattax
+1 for a basic tutorial that still includes form authentication and password hashing.
Andrew Coleson
A: 

It seems this may have your answer: http://www.homeandlearn.co.uk/php/php14p3.html

Woot4Moo
+1  A: 

You can use an include file that has the code to check if the user is logged in, then include this at the top of every page you want to validate the login.

Shawn Steward
A: 

Also, look into creating a php header file that does that login check for you, and then you just have to include that header at the top of each page that you want secured.

Chetan