PHP Authentication / Authorization
One of the big things I needed to do when switching from ASP.NET to PHP was to figure out how to do authentication and authorization. ASP.NET is pretty strong in this area as it’s very easy to set up forms authentication and authorization rules for a site. I found that things weren’t so straightforward with PHP so I took it upon myself to put together a simple example to show how to accomplish this.
The example has a basic premise: we have a log in page and a secured page. The user cannot view the secured page until he authenticates via the log in page. Conversely, the user cannot view the log in page if he has already been authenticated. If he logs out then he will be taken back to the login page.
A working example of this can be found right here. You can also download the code for this example right here. You’ll need a local web server that will run PHP 5 and MySQL.
The example will try to authenticate a user against the database. If the authentication is successful a session key is written and the user is redirected to the secured page. Most of the code is self explanatory but I wanted to highlight the following:
< ?php session_start(); //check if person is already logged in and if so redirect to index page if(isset($_SESSION['email'])) { header('Location: login-example-index.php'); } ?>
This code is on our log in page. It’s basically checking to see if the person has already authenticated. If so we want to forward them to the secured page.
A similar snippet is on the secured page and it checks to make sure the user has been authenticated. If not it’ll send them back to the login page.
Hope this simple example will help anyone trying to put together some basic authentication. Please note that this is a very simple example and something a little more secure and robust should be used in a production setting that has sensitive data.
Friday, June 12th, 2009

No Comments For “PHP Authentication / Authorization”
Leave A Comment