You can do this easily using
sessions, a few session variables, and a MySQL table. Although there are many ways
to implement this feature, checking for an existing session variable (namely $username) is
sufficient. If that variable exists, the user can automatically log in to the site. If not, a
login form is presented.
?– Note By default, the session.cookie_lifetime configuration directive is set to 0, which means
that the cookie will not persist if the browser is restarted. Therefore, you should change this value to an
appropriate number of seconds in order to make the session persist over a period of time.
The MySQL table, users, is presented in Listing 18-1.
Listing 18-1. The users Table
CREATE TABLE users (
id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
username VARCHAR(10) NOT NULL,
pswd VARCHAR(10) NOT NULL,
PRIMARY KEY(id)
);
A snippet (login.html) used to display the login form to the user if a valid session is
not found is presented next:
Finally, the logic used to manage the auto-login process follows:
460 CHAPTER 18 ?– SESSION HANDLERS
session_start();
// Has a session been initiated previously?
if (! isset($_SESSION['username'])) {
// If no previous session, has the user submitted the form?
if (isset($_POST['username']))
{
$username = mysqli_real_escape_string($_POST['username']);
$pswd = mysqli_real_escape_string($_POST['pswd']);
// Connect to the MySQL server and select the database
mysql_connect("localhost","webuser","secret");
mysql_select_db("chapter18");
// Look for the user in the users table.
Pages:
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541