PAGES THAT REMEMBER: SIMPLE LOGIN AND MULTIPAGE FORMS (Web hosting plans)
PAGES THAT REMEMBER: SIMPLE LOGIN AND MULTIPAGE FORMS // if there’s a match, set a session variable $_SESSION[’authenticated’] = ‘Jethro Tull’; break; } } // if the session variable has been set, redirect if (isset($_SESSION[’authenticated’])) { header(’Location: http://localhost/phpsolutions/sessions/ . menu.php’); exit; } // if the session variable hasn’t been set, refuse entry else { $error = ‘Invalid username or password.’; } } // error message to display if text file not readable else { $error = ‘Login facility unavailable. Please try later.’; } } ?> PHP Solution 7-2 explains how the original script reads the external text file, so I ll concentrate on the new code. First, the entire script has been moved above the DOCTYPE declaration and is enveloped in a conditional statement. The name attribute of the submit button is login, so array_key_exists() checks whether it s in the $_POST array to ensure that the script runs only when the form is submitted. You need to initiate a session only if the form has been submitted, so the first command inside the conditional statement is session_start(). Although the user input is unlikely to contain quotes, it s wise to strip any backslashes from the $_POST array, so corefuncs.php is included and a call made to nukeMagicQuotes() (see Chapter 3). The next section of new code is inside the loop that extracts the name and password from each line. If the record matches username and pwd in the $_POST array, the script creates a variable called $_SESSION[’authenticated’] and assigns it the name of one of the great folk-rock bands of the 70s. There s nothing magic about either of these (apart from Jethro Tull s music); I ve chosen the name and value of the variable arbitrarily. All that matters is a session variable is created. Since you re looking for only one record, you can use break to exit the loop as soon as a match is found. The rest of the script checks whether the session variable has been created. If it has, the user is redirected to menu.php by the header() function (adjust the URL to match your setup, if necessary), and exit prevents the script from running any further. If the session variable hasn t been set, the username and/or password weren t found, and a suitable error message is prepared. The final else clause prepares a different error message in the event that the external file couldn t be read. 243
From our experience, we can recommend PHP5 Web Hosting services, if you need affordable webhost to host and run your web application.