PAGES THAT REMEMBER: SIMPLE LOGIN AND MULTIPAGE FORMS 3. Save login.php and test it. It should work the same as before, but be more secure. Check your code if necessary with login_encrypted.php in the download files. PHP Solutions 9-3 to 9-7 show you how to create a simple, yet effective user authentica tion system that doesn t require a database back end. However, it does have its limitations. Above all, it s essential that the text file containing the usernames and passwords be out side the server root. Even though the passwords are encrypted, knowing the usernames reduces the effort that an attacker needs to try to break through your security. Another weakness is that the salt is the username. Ideally, you should create a random salt for each password, but you need to store it somewhere. If it s in the same file as the usernames, they would both be exposed at the same time. Using a database for user authentication gets around many of these problems. It involves more coding, but is likely to be more secure. Also, once you get more than a few records, querying a database is usually much faster than looping through a text file line by line. Of course, the weakest link in most security systems lies in easily guessed passwords, or users revealing their login details (intentionally or otherwise) to unauthorized users. Chapter 15 covers user authentication with a database. Setting a time limit on sessions Setting a time limit on a PHP session is easy. When the session first starts, typically when the user logs in, store the current time in a session variable. Then compare it with the lat est time whenever the user does anything that triggers a page to load. If the difference is greater than a predetermined limit, destroy the session and its variables. Otherwise, update the variable to the latest time. PHP Solution 9-8: Ending a session after a period of inactivity This assumes that you have set up a login system as described in PHP Solutions 9-3 to 9-7. The completed scripts are in login_timeout.php, menu_timeout.php, and secretpage_timeout.php in the download files for this chapter. 1. You need to store the current time after the user s credentials have been authenticated, but before the script redirects the user to the restricted part of the site. Locate the redirect code in login.php (around line 31), and insert the new code highlighted in bold as follows: // if the session variable has been set, redirect if (isset($_SESSION[’authenticated’])) { // get the time the session started $_SESSION[’start’] = time(); header(’Location: http://localhost/phpsolutions/sessions/menu.php’); exit; } The time() function returns a current timestamp. By storing it in $_SESSION[’start’], it becomes available to every page that begins with session_start(). 253
If you are in need for cheap and reliable webhost to host your website, we recommend http web server services.