Authentication script

When the login <form> is submitted, the POST variables are processed by the authentication script shown in Example 9-9. The authentication is performed by passing a handle to a connected MySQL server, the username, and the password to the function authenticateUser( ). The function executes a query to find the user row with the same username and encrypted password. As with the code in Example 9-7, we use the first two characters from the username as the salt string to the crypt( ) function.

The Boolean control variable $authenticated is set to the return value of the authenticateUser( ) function. If $authenticated is true, the username is registered as the $authenticatedUser session variable and the IP address of the client machine from which the request originated as the $loginIpAddress session variable.

If the authentication fails and $authenticated is set to false, the $loginMessage session variable is registered containing the appropriate message to display on the login <form> as shown in Figure 9-3. In Example 9-9 we always relocate back to the login page, keeping the code reasonably simple. An alternative would be to relocate back to a customer welcome page when authentication succeeds and relocate back to the login page only when authentication fails.

Logout script

A separate script is called when a user logs out of the application. Example 9-10 shows the script that unregisters the $authenticatedUser session variable, registers the $loginMessage variable containing the appropriate message, and relocates back to the login script. The login script checks if the $loginMessage session variable is registered and displays the message that the user has logged out.