Login

Introduction

Login is a common feature in websites. It is implemented by combining HTML form, database query and session.

When a user logs in, the username and password in HTML form are sent to the server. (HTML form)
The server checks the username and password in the database. (Database query)
If the username and password are correct, the server creates a session for the user. (Session)
When the user logs out, the server destroys the session. (Session)

Code - HTML form


<form action="login.php" method="post">
	Username: <input type="text" name="username"><br>
	Password: <input type="password" name="password"><br>
	<input type="submit" value="Login">
</form>
	

Code - PHP to check login and create session


<?php
	// POST username and password
	$username = $_POST["username"];
	$password = $_POST["password"];

	// Database file location
	$dbname = "sqlite.db";
	
	// Create connection
	$conn = new SQLite3($dbname);
	
	// Check connection
	if (!$conn) {
		die("Connection failed: " . $conn->lastErrorMsg());
	} else {
		// if connected successfully, check username and password
		$sql = "SELECT * FROM accounts WHERE username='$username' AND password='$password'";
		
		// Execute query
		$result = $conn->query($sql);
		// if there is a row found, it means username and password are correct
		if ($result->fetchArray()) {
			// start session
			session_start();
			// set session variable
			$_SESSION["username"] = $username;
			// redirect to welcome.php
			echo "Welcome " . $_SESSION["username"];
		} else {
			echo "Username or password is incorrect.";
		}

		// close connection
		$conn->close();
	}
?>
	

Demo

SQLite Content:
SQLite Content

Test page:
Open in new window

Task

Download sqlite.db file that stores user accounts.

Modify the above code:
1. Do not show error after login and visit login.php again.
Hints: Check session variable first in login.php

2. Create a logout button that destroys the session.