The above login mechanism works great; however, by the time the user is redirected to the home page, the website has, of course, forgotten all about the successful authentication! This is because HTTP is a stateless protocol, meaning there is no knowledge of what happened previously nor of what is about to happen. As a workaround, developers have devised a great solution known as
session management, which can track a user's activity as he navigates from one page to the next. Fortunately for you, PHP excels particularly well at this capability. Therefore, let's revise the relevant part of the
login.php script to use PHP's session handling feature to start a new session and then assign the user's username to a session variable. I've bolded the lines added to the revised part of the login script:
All that remains is to create the home page. The following code determines whether a session variable named username already exists, and if so provides a customized welcome message. If the variable doesn't exist, a registration and login link is provided:
Obviously, this solution could use a bit of additional work, notably in terms of validating the login form and properly informing the user should the login attempt fail. However a pretty slick Ajax-driven validation feature could be added to the process in order to perform the validation in real-time without ever leaving the login page. Additionally, a logout feature should be added, preferably one which integrates with the login feature in order to either leave the user logged in for a significant period of time or automatically log the user off as soon as the browser window closes. Either way, the material provided in this tutorial should be enough to help you get started exploring these powerful features!