Implementing User Authentication Mechanism
the PHP Login System with MySQL tutorial Includes all essential features: registration, login, session handling, logout, and password reset.
1. Create the MySQL Table
Run this SQL in your MySQL database:
CREATE TABLE users (
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(50) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
2. Database Connection File (config.php
)
<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'demo');
$link = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
?>
3. User Registration (register.php
)
Uses password_hash()
to securely store the password.
<?php
require_once "config.php";
$username = $password = $confirm_password = "";
$username_err = $password_err = $confirm_password_err = "";
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(empty(trim($_POST["username"]))){
$username_err = "Please enter a username.";
} else{
$sql = "SELECT id FROM users WHERE username = ?";
if($stmt = mysqli_prepare($link, $sql)){
mysqli_stmt_bind_param($stmt, "s", $param_username);
$param_username = trim($_POST["username"]);
if(mysqli_stmt_execute($stmt)){
mysqli_stmt_store_result($stmt);
if(mysqli_stmt_num_rows($stmt) == 1){
$username_err = "This username is already taken.";
} else{
$username = trim($_POST["username"]);
}
} else{
echo "Something went wrong.";
}
mysqli_stmt_close($stmt);
}
}
if(empty(trim($_POST["password"]))){
$password_err = "Please enter a password.";
} elseif(strlen(trim($_POST["password"])) < 6){
$password_err = "Password must have at least 6 characters.";
} else{
$password = trim($_POST["password"]);
}
if(empty(trim($_POST["confirm_password"]))){
$confirm_password_err = "Please confirm password.";
} else{
$confirm_password = trim($_POST["confirm_password"]);
if(empty($password_err) && ($password != $confirm_password)){
$confirm_password_err = "Passwords did not match.";
}
}
if(empty($username_err) && empty($password_err) && empty($confirm_password_err)){
$sql = "INSERT INTO users (username, password) VALUES (?, ?)";
if($stmt = mysqli_prepare($link, $sql)){
mysqli_stmt_bind_param($stmt, "ss", $param_username, $param_password);
$param_username = $username;
$param_password = password_hash($password, PASSWORD_DEFAULT);
if(mysqli_stmt_execute($stmt)){
header("location: login.php");
} else{
echo "Something went wrong.";
}
mysqli_stmt_close($stmt);
}
}
mysqli_close($link);
}
?>
<!-- HTML Form -->
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<label>Username</label>
<input type="text" name="username" value="<?php echo $username; ?>">
<span><?php echo $username_err; ?></span>
<label>Password</label>
<input type="password" name="password">
<span><?php echo $password_err; ?></span>
<label>Confirm Password</label>
<input type="password" name="confirm_password">
<span><?php echo $confirm_password_err; ?></span>
<input type="submit" value="Register">
<a href="login.php">Already have an account? Login here.</a>
</form>
4. User Login (login.php
)
Verifies credentials using password_verify()
and uses PHP sessions.
<?php
session_start();
require_once "config.php";
$username = $password = "";
$username_err = $password_err = "";
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(empty(trim($_POST["username"]))){
$username_err = "Please enter username.";
} else{
$username = trim($_POST["username"]);
}
if(empty(trim($_POST["password"]))){
$password_err = "Please enter your password.";
} else{
$password = trim($_POST["password"]);
}
if(empty($username_err) && empty($password_err)){
$sql = "SELECT id, username, password FROM users WHERE username = ?";
if($stmt = mysqli_prepare($link, $sql)){
mysqli_stmt_bind_param($stmt, "s", $param_username);
$param_username = $username;
if(mysqli_stmt_execute($stmt)){
mysqli_stmt_store_result($stmt);
if(mysqli_stmt_num_rows($stmt) == 1){
mysqli_stmt_bind_result($stmt, $id, $username, $hashed_password);
if(mysqli_stmt_fetch($stmt)){
if(password_verify($password, $hashed_password)){
session_start();
$_SESSION["loggedin"] = true;
$_SESSION["id"] = $id;
$_SESSION["username"] = $username;
header("location: welcome.php");
} else{
$password_err = "Invalid password.";
}
}
} else{
$username_err = "No account found.";
}
} else{
echo "Something went wrong.";
}
mysqli_stmt_close($stmt);
}
}
mysqli_close($link);
}
?>
<!-- HTML Form -->
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<label>Username</label>
<input type="text" name="username">
<span><?php echo $username_err; ?></span>
<label>Password</label>
<input type="password" name="password">
<span><?php echo $password_err; ?></span>
<input type="submit" value="Login">
</form>
5. Welcome Page (welcome.php
)
<?php
session_start();
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: login.php");
exit;
}
?>
<!DOCTYPE html>
<html>
<head><title>Welcome</title></head>
<body>
<h1>Hello, <?php echo htmlspecialchars($_SESSION["username"]); ?>!</h1>
<p><a href="reset-password.php">Reset Password</a> | <a href="logout.php">Logout</a></p>
</body>
</html>
6. Logout Script (logout.php
)
<?php
session_start();
$_SESSION = array();
session_destroy();
header("location: login.php");
exit;
?>
7. Password Reset (reset-password.php
)
<?php
session_start();
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: login.php");
exit;
}
require_once "config.php";
$new_password = $confirm_password = "";
$new_password_err = $confirm_password_err = "";
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(empty(trim($_POST["new_password"]))){
$new_password_err = "Please enter the new password.";
} elseif(strlen(trim($_POST["new_password"])) < 6){
$new_password_err = "Password must have at least 6 characters.";
} else{
$new_password = trim($_POST["new_password"]);
}
if(empty(trim($_POST["confirm_password"]))){
$confirm_password_err = "Please confirm the password.";
} else{
$confirm_password = trim($_POST["confirm_password"]);
if(empty($new_password_err) && ($new_password != $confirm_password)){
$confirm_password_err = "Passwords do not match.";
}
}
if(empty($new_password_err) && empty($confirm_password_err)){
$sql = "UPDATE users SET password = ? WHERE id = ?";
if($stmt = mysqli_prepare($link, $sql)){
mysqli_stmt_bind_param($stmt, "si", $param_password, $param_id);
$param_password = password_hash($new_password, PASSWORD_DEFAULT);
$param_id = $_SESSION["id"];
if(mysqli_stmt_execute($stmt)){
session_destroy();
header("location: login.php");
exit();
} else{
echo "Something went wrong.";
}
mysqli_stmt_close($stmt);
}
}
mysqli_close($link);
}
?>
<!-- HTML Form -->
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<label>New Password</label>
<input type="password" name="new_password">
<span><?php echo $new_password_err; ?></span>
<label>Confirm Password</label>
<input type="password" name="confirm_password">
<span><?php echo $confirm_password_err; ?></span>
<input type="submit" value="Submit">
<a href="welcome.php">Cancel</a>
</form>