Now, if you look closely at the HTML markup on the previous page, you'll see that the form references the script "login.php". This PHP script actually performs the task of validating the user information entered into the form against an external source. In this case, the external source is the system's "/etc/passwd" file. Here's the script which performs the validation: Pay special attention to the authenticate() function, which forms the core of the script above. This is the function that actually does the hard work of accepting a username/password combo, iterating through the password file, crypt()-ing and matching the user's input against the encrypted data in the file, and finally returning a result code based on the results of the comparison. In case you're wondering about the actual mechanics of the validation, it's fairly simple. The authenticate() reads the system's password file ("/etc/passwd" here), looks for a line beginning with the specified username, and extracts the first two letters of the corresponding encrypted password string. These two characters serve as the "salt" for the encryption process. Next, the cleartext password is encrypted with PHP's crypt() function and the extracted "salt", with the result checked against the encrypted value in the password file. If the two match, it implies that the supplied password was correct; if they don't, it implies that the password was wrong. Either way, the result of this authentication procedure is then returned to the caller via a result code. Assuming that the user has been successfully authenticated, a PHP session is instantiated via the session_start() function, and some session variables are registered. These session variables remain active for the duration of the user's visit to the site. In the example above, I've registered $SESSION (a flag variable to indicate that a session is active) and $SESSION_UNAME (the user's account username) as session variables Note also that I have found it a good practice to capitalize session variable names, so as to distinguish them from the local variables found in individual script. Again, this is a personal quirk - feel free to ignore it if you think it's stupid. Once all the session variables have been set up, the browser is redirected to the protected page, "inner.sanctum.php". We'll look at that, and also at the error handler "error.php" shortly - but first, let's look at an alternative scenario, which uses a database for user validation.
blog comments powered by Disqus |