How to develop Projects Using PHP and Mysql -part 2
/auth/
- register.php
→ User registration form.
- login.php
→ User authentication.
- logout.php
→ Logout script.
1.register.php
Type 1: Using mysqli query method
<?php require_once '../database/db_config.php'; session_start(); if ($_SERVER["REQUEST_METHOD"] ==
"POST") { $name =
trim($_POST['name']); $email =
trim($_POST['email']); $password =
trim($_POST['password']); $confirm_password =
trim($_POST['confirm_password']); $phone =
trim($_POST['phone']); $role =
trim($_POST['role']); $errors = []; // Validate required fields if (empty($name) ||
empty($email) || empty($password) || empty($confirm_password) ||
empty($role)) { $errors[]
= "All fields except phone are required!"; } // Validate email format if (!filter_var($email,
FILTER_VALIDATE_EMAIL)) { $errors[]
= "Invalid email format!"; } // Validate phone number
(optional, must be numeric if provided) if (!empty($phone)
&& !preg_match("/^[0-9]{10,15}$/", $phone)) { $errors[]
= "Invalid phone number!"; } // Check password length if (strlen($password) <
6) { $errors[]
= "Password must be at least 6 characters!"; } // Check if passwords match if ($password !==
$confirm_password) { $errors[]
= "Passwords do not match!"; } // Restrict multiple Admins if ($role ===
"admin") { $admin_check_query
= "SELECT id FROM users WHERE role = 'admin'"; $admin_result
= mysqli_query($conn, $admin_check_query); if
(mysqli_num_rows($admin_result) > 0) { $errors[]
= "An Admin already exists! Only one Admin is allowed."; } } // Check if email already
exists $email_check_query =
"SELECT id FROM users WHERE email = '$email'"; $email_result =
mysqli_query($conn, $email_check_query); if
(mysqli_num_rows($email_result) > 0) { $errors[]
= "Email already registered!"; } // If no errors, insert user if (empty($errors)) { $hashed_password
= password_hash($password, PASSWORD_BCRYPT); $insert_query
= "INSERT INTO users (name, email, password, phone, role) VALUES
('$name', '$email', '$hashed_password', '$phone', '$role')"; if
(mysqli_query($conn, $insert_query)) { $_SESSION['success']
= "Registration successful! You can now log in."; header("Location:
login.php"); exit(); }
else { $errors[]
= "Registration failed! Please try again."; } } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta
charset="UTF-8"> <meta
name="viewport" content="width=device-width,
initial-scale=1.0"> <title>Register</title> <link
rel="stylesheet" href="../assets/css/style.css"> </head> <body> <?php include '../includes/navbar.php'; ?> <div class="container"> <h2>Register</h2> <?php if (!empty($errors)) { echo
'<div class="error">'; foreach
($errors as $error) { echo
"<p>$error</p>"; } echo
'</div>'; } if
(isset($_SESSION['success'])) { echo
'<div class="success"><p>' . $_SESSION['success'] .
'</p></div>'; unset($_SESSION['success']); } ?> <form
action="register.php" method="POST"> <label
for="name">Full Name:</label> <input
type="text" name="name" required> <label
for="email">Email:</label> <input
type="email" name="email" required> <label
for="password">Password:</label> <input
type="password" name="password" required> <label
for="confirm_password">Confirm Password:</label> <input
type="password" name="confirm_password" required> <label
for="phone">Phone (Optional):</label> <input
type="text" name="phone"> <label
for="role">Select Role:</label> <select
name="role" required> <option
value="user">User</option> <option
value="admin">Admin</option> </select> <button
type="submit">Register</button> </form> <p>Already have an
account? <a href="login.php">Login here</a>.</p> </div> <?php include '../includes/footer.php'; ?> </body> </html>
|
Code Explanation of the Registration Code in PHP using MySQLi
1. Including Database Configuration &
Session Start
require_once '../database/db_config.php';
session_start();
- require_once
is used to include the database configuration file (db_config.php). It
ensures that the file is included only once to prevent multiple inclusions
that could cause errors.
- session_start();
initializes a session to store messages like success or error
notifications.
2. Handling the Form Submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
- Checks
if the form is submitted using the POST method.
- $_SERVER["REQUEST_METHOD"]
ensures the script runs only when the form is submitted.
3. Retrieving and Cleaning Form Data
$name = trim($_POST['name']);
$email = trim($_POST['email']);
$password = trim($_POST['password']);
$confirm_password
= trim($_POST['confirm_password']);
$phone = trim($_POST['phone']);
$role = trim($_POST['role']);
- trim()
removes unwanted spaces before and after the input.
- $_POST['field_name']
retrieves user input from the form.
4. Initializing an Errors Array
$errors = [];
- An
empty array is created to store validation errors.
5. Validating Required Fields
if (empty($name) || empty($email) || empty($password) || empty($confirm_password) || empty($role)) {
$errors[]
= "All fields except phone are required!";
}
- Checks
if any required field is empty.
- If
any field is missing, an error message is added to the $errors array.
6. Validating Email Format
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[]
= "Invalid email format!";
}
- filter_var()
checks if the provided email is in a valid format.
- If
not valid, an error message is added.
7. Validating Phone Number (Optional)
if (!empty($phone) && !preg_match("/^[0-9]{10,15}$/", $phone)) {
$errors[]
= "Invalid phone number!";
}
- If
a phone number is provided, it must contain only numbers and be 10
to 15 digits long.
- preg_match()
is used for pattern matching.
8. Validating Password Length
if (strlen($password) < 6) {
$errors[]
= "Password must be at least 6 characters!";
}
- Ensures
the password is at least 6 characters long.
9. Checking if Passwords Match
if ($password !== $confirm_password) {
$errors[]
= "Passwords do not match!";
}
- Ensures
that the password and confirm_password fields match.
10. Restricting Multiple Admins
if ($role === "admin") {
$admin_check_query
= "SELECT id FROM users WHERE role = 'admin'";
$admin_result
= mysqli_query($conn, $admin_check_query);
if (mysqli_num_rows($admin_result)
> 0) {
$errors[]
= "An Admin already exists! Only one Admin is allowed.";
}
}
- If
the user selects the Admin role, the script checks if an admin
already exists in the database.
- mysqli_num_rows($admin_result)
> 0 means at least one admin exists, so another one is not
allowed.
11. Checking if Email Already Exists
$email_check_query = "SELECT id FROM users WHERE email = '$email'";
$email_result
= mysqli_query($conn, $email_check_query);
if (mysqli_num_rows($email_result)
> 0) {
$errors[]
= "Email already registered!";
}
- The
query checks if the email is already registered.
- If
mysqli_num_rows() returns more than 0, it means the email exists,
and an error message is added.
12. If No Errors, Insert the User
if (empty($errors)) {
$hashed_password
= password_hash($password, PASSWORD_BCRYPT);
- If
there are no errors, the password is hashed using password_hash()
with the BCRYPT algorithm.
$insert_query = "INSERT INTO users (name, email, password, phone, role)
VALUES ('$name', '$email',
'$hashed_password', '$phone', '$role')";
- An
SQL query is created to insert user data into the database.
if (mysqli_query($conn, $insert_query)) {
$_SESSION['success']
= "Registration successful! You can now log in.";
header("Location:
login.php");
exit();
} else {
$errors[]
= "Registration failed! Please try again.";
}
}
- If
the query executes successfully, a success message is stored in $_SESSION['success'],
and the user is redirected to login.php.
- If
the query fails, an error message is added to $errors.
13. HTML Form & Error Messages
if (!empty($errors)) {
echo '<div
class="error">';
foreach
($errors as $error) {
echo
"<p>$error</p>";
}
echo '</div>';
}
- If
there are errors, they are displayed in an <div> with an error
class.
if (isset($_SESSION['success'])) {
echo '<div
class="success"><p>' . $_SESSION['success'] . '</p></div>';
unset($_SESSION['success']);
}
- If
the session contains a success message, it is displayed and then
removed.
14. The Registration Form
<form action="register.php" method="POST">
<label for="name">Full
Name:</label>
<input type="text"
name="name" required>
<label for="email">Email:</label>
<input type="email"
name="email" required>
<label for="password">Password:</label>
<input type="password"
name="password" required>
<label for="confirm_password">Confirm
Password:</label>
<input type="password"
name="confirm_password" required>
<label for="phone">Phone
(Optional):</label>
<input type="text"
name="phone">
<label for="role">Select
Role:</label>
<select name="role"
required>
<option
value="user">User</option>
<option
value="admin">Admin</option>
</select>
<button type="submit">Register</button>
</form>
- A
simple form with:
- name,
email, password, confirm_password, phone, and role fields.
- A
submit button to send data.
15. Linking External Files
<?php include '../includes/navbar.php'; ?>
<?php include '../includes/footer.php'; ?>
- navbar.php
includes the navigation bar.
- footer.php
includes the footer.
Summary of the Code
1.
Handles Form Submission
– Checks if the form is submitted using POST.
2.
Validates Input
– Ensures required fields are filled and formatted correctly.
3.
Checks for Existing Email/Admin
– Prevents duplicate emails and multiple admins.
4.
Hashes Password
– Encrypts the password before storing it.
5.
Inserts User Data
– Saves the user details in the database.
6.
Displays Errors/Success Messages
– Shows validation messages to the user.
7.
Redirects on Success
– Redirects the user to login.php if registration is successful.
Type 2: Using Prepared Statement:
<?php require_once '../database/db_config.php'; session_start(); if ($_SERVER["REQUEST_METHOD"] ==
"POST") { $name =
trim($_POST['name']); $email =
trim($_POST['email']); $password =
trim($_POST['password']); $confirm_password =
trim($_POST['confirm_password']); $phone =
trim($_POST['phone']); $role =
trim($_POST['role']); $errors = []; // Validate required fields if (empty($name) ||
empty($email) || empty($password) || empty($confirm_password) ||
empty($role)) { $errors[]
= "All fields except phone are required!"; } // Validate email format if (!filter_var($email,
FILTER_VALIDATE_EMAIL)) { $errors[]
= "Invalid email format!"; } // Validate phone number
(optional, must be numeric if provided) if (!empty($phone)
&& !preg_match("/^[0-9]{10,15}$/", $phone)) { $errors[]
= "Invalid phone number!"; } // Check password length if (strlen($password) <
6) { $errors[]
= "Password must be at least 6 characters!"; } // Check if passwords match if ($password !==
$confirm_password) { $errors[]
= "Passwords do not match!"; } // Restrict multiple Admins if ($role ===
"admin") { $admin_check_query
= "SELECT id FROM users WHERE role = 'admin'"; $admin_result
= mysqli_query($conn, $admin_check_query); if
(mysqli_num_rows($admin_result) > 0) { $errors[]
= "An Admin already exists! Only one Admin is allowed."; } } // Check if email already
exists $email_check_query =
"SELECT id FROM users WHERE email = ?"; $stmt =
mysqli_prepare($conn, $email_check_query); mysqli_stmt_bind_param($stmt,
"s", $email); mysqli_stmt_execute($stmt); $email_result =
mysqli_stmt_get_result($stmt); if
(mysqli_num_rows($email_result) > 0) { $errors[]
= "Email already registered!"; } // If no errors, insert user if (empty($errors)) { $hashed_password
= password_hash($password, PASSWORD_BCRYPT); $insert_query
= "INSERT INTO users (name, email, password, phone, role) VALUES (?, ?,
?, ?, ?)"; $stmt
= mysqli_prepare($conn, $insert_query); mysqli_stmt_bind_param($stmt,
"sssss", $name, $email, $hashed_password, $phone, $role); if
(mysqli_stmt_execute($stmt)) { $_SESSION['success']
= "Registration successful! You can now log in."; header("Location:
login.php"); exit(); }
else { $errors[]
= "Registration failed! Please try again."; } } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta
charset="UTF-8"> <meta
name="viewport" content="width=device-width,
initial-scale=1.0"> <title>Register</title> <link
rel="stylesheet" href="../assets/css/style.css"> </head> <body> <?php include '../includes/navbar.php'; ?> <div class="container"> <h2>Register</h2> <?php if (!empty($errors)) { echo
'<div class="error">'; foreach
($errors as $error) { echo
"<p>$error</p>"; } echo
'</div>'; } if
(isset($_SESSION['success'])) { echo
'<div class="success"><p>' . $_SESSION['success'] .
'</p></div>'; unset($_SESSION['success']); } ?> <form
action="register.php" method="POST"> <label
for="name">Full Name:</label> <input
type="text" name="name" required> <label
for="email">Email:</label> <input
type="email" name="email" required> <label
for="password">Password:</label> <input
type="password" name="password" required> <label
for="confirm_password">Confirm Password:</label> <input
type="password" name="confirm_password" required> <label
for="phone">Phone (Optional):</label> <input
type="text" name="phone"> <label
for="role">Select Role:</label> <select
name="role" required> <option
value="user">User</option> <option
value="admin">Admin</option> </select> <button
type="submit">Register</button> </form> <p>Already have an
account? <a href="login.php">Login here</a>.</p> </div> <?php include '../includes/footer.php'; ?> </body> </html>
|
Explaination Of Code By Step-by-Step
1️⃣ Import Database Configuration &
Start Session
require_once '../database/db_config.php';
session_start();
- require_once
'../database/db_config.php';
- Includes
the database configuration file to connect to the MySQL database.
- session_start();
- Starts
a PHP session to store messages (e.g., success/failure
notifications) across pages.
2️⃣ Handle Form Submission (POST
Request)
if ($_SERVER["REQUEST_METHOD"] == "POST") {
- Checks
if the form is submitted via the POST method.
- Prevents
direct URL access to this script.
3️⃣ Retrieve & Sanitize Form Data
$name = trim($_POST['name']);
$email = trim($_POST['email']);
$password = trim($_POST['password']);
$confirm_password = trim($_POST['confirm_password']);
$phone = trim($_POST['phone']);
$role = trim($_POST['role']);
- Retrieves
form input values from $_POST.
- trim()
removes extra spaces from input values.
- Ensures
no unnecessary spaces in user input.
4️⃣ Initialize an Error Array
$errors = [];
- Creates
an empty array to store validation errors.
5️⃣ Validate Required Fields
if (empty($name) || empty($email) || empty($password) || empty($confirm_password) || empty($role)) {
$errors[] = "All
fields except phone are required!";
}
- Checks
if any required field is empty.
- Adds
an error message to $errors[] if missing.
6️⃣ Validate Email Format
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = "Invalid
email format!";
}
- Uses
filter_var() to validate email format.
- Adds
an error if the email is not properly formatted.
7️⃣ Validate Phone Number (Optional)
if (!empty($phone) && !preg_match("/^[0-9]{10,15}$/", $phone)) {
$errors[] = "Invalid
phone number!";
}
- If
phone is provided, it must contain only numbers (0-9).
- Must
be between 10 to 15 digits.
- Uses
preg_match() for regular expression validation.
8️⃣ Validate Password Length
if (strlen($password) < 6) {
$errors[] = "Password
must be at least 6 characters!";
}
- Ensures
password is at least 6 characters long.
9️⃣ Check If Passwords Match
if ($password !== $confirm_password) {
$errors[] = "Passwords
do not match!";
}
- Ensures
the confirmed password matches the original password.
🔟
Restrict Multiple Admins
if ($role === "admin") {
$admin_check_query
= "SELECT id FROM users WHERE role = 'admin'";
$admin_result
= mysqli_query($conn, $admin_check_query);
if (mysqli_num_rows($admin_result)
> 0) {
$errors[]
= "An Admin already exists! Only one Admin is allowed.";
}
}
- If
the user selects Admin role, it checks if an Admin already
exists.
- Executes:
SELECT id FROM users WHERE role = 'admin'
- If
any result is found, it prevents another Admin registration.
1️⃣1️⃣ Check for
Duplicate Email
$email_check_query = "SELECT id FROM users WHERE email = ?";
$stmt = mysqli_prepare($conn, $email_check_query);
mysqli_stmt_bind_param($stmt, "s", $email);
mysqli_stmt_execute($stmt);
$email_result = mysqli_stmt_get_result($stmt);
if (mysqli_num_rows($email_result) > 0) {
$errors[] = "Email
already registered!";
}
- Uses
a prepared statement to check if the email already exists in
the database.
- If
the email is found, registration is denied.
1️⃣2️⃣ Insert User into
Database (If No Errors)
if (empty($errors)) {
$hashed_password
= password_hash($password, PASSWORD_BCRYPT);
$insert_query
= "INSERT INTO users (name, email, password, phone, role) VALUES (?, ?, ?,
?, ?)";
$stmt = mysqli_prepare($conn,
$insert_query);
mysqli_stmt_bind_param($stmt,
"sssss", $name, $email, $hashed_password, $phone, $role);
if (mysqli_stmt_execute($stmt))
{
$_SESSION['success']
= "Registration successful! You can now log in.";
header("Location:
login.php");
exit();
} else {
$errors[]
= "Registration failed! Please try again.";
}
}
- Hashes
the password using password_hash($password,
PASSWORD_BCRYPT).
- Uses
a prepared statement to securely insert user data.
- Redirects
to login page on successful registration.
1️⃣3️⃣ Display Errors
and Success Messages
if (!empty($errors)) {
echo '<div
class="error">';
foreach ($errors
as $error) {
echo "<p>$error</p>";
}
echo '</div>';
}
if (isset($_SESSION['success'])) {
echo '<div
class="success"><p>' . $_SESSION['success'] . '</p></div>';
unset($_SESSION['success']);
}
- If
there are errors, they are displayed inside <div
class="error">.
- If
registration is successful, a success message is shown.
1️⃣4️⃣ Registration Form
<form action="register.php" method="POST">
<label for="name">Full
Name:</label>
<input type="text"
name="name" required>
<label for="email">Email:</label>
<input type="email"
name="email" required>
<label for="password">Password:</label>
<input type="password"
name="password" required>
<label for="confirm_password">Confirm
Password:</label>
<input type="password"
name="confirm_password" required>
<label for="phone">Phone
(Optional):</label>
<input type="text"
name="phone">
<label for="role">Select
Role:</label>
<select name="role"
required>
<option
value="user">User</option>
<option
value="admin">Admin</option>
</select>
<button type="submit">Register</button>
</form>
- A
simple registration form.
- Uses
<select> dropdown for role selection (user or admin).
1️⃣5️⃣ Include Navbar
and Footer
<?php include '../includes/navbar.php'; ?>
<?php include '../includes/footer.php'; ?>
- Includes
common navigation bar and footer for the page.
📌
Summary of Features
✔ Ensures
only one Admin exists
✔ Validates user input
(email, password, phone, etc.)
✔ Hashes passwords for
security
✔ Prevents duplicate
emails
✔ Uses prepared
statements to prevent SQL Injection
✔ Displays errors and
success messages
2.login.php
✅ login.php
(Using Only MySQLi Query Functions)
<?php require_once '../database/db_config.php'; session_start(); if ($_SERVER["REQUEST_METHOD"] ==
"POST") { $email = trim($_POST['email']); $password =
trim($_POST['password']); $errors = []; // Validate input fields if (empty($email) ||
empty($password)) { $errors[]
= "Email and Password are required!"; } elseif (!filter_var($email,
FILTER_VALIDATE_EMAIL)) { $errors[]
= "Invalid email format!"; } if (empty($errors)) { // Fetch
user details from the database $query =
"SELECT * FROM users WHERE email = '$email'"; $result =
mysqli_query($conn, $query); if ($row
= mysqli_fetch_assoc($result)) {
// Verify the hashed password
if (password_verify($password, $row['password'])) {
$_SESSION['user_id'] = $row['id'];
$_SESSION['user_name'] = $row['name'];
$_SESSION['user_email'] = $row['email'];
$_SESSION['user_role'] = $row['role'];
// Redirect user based on role
if ($row['role'] === 'admin') {
header("Location: ../admin/admin_dashboard.php");
} else {
header("Location: ../user/user_dashboard.php");
}
exit();
} else {
$errors[] = "Incorrect password!";
} } else {
$errors[] = "No account found with this email!"; } } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta
charset="UTF-8"> <meta
name="viewport" content="width=device-width,
initial-scale=1.0"> <title>Login</title> <link
rel="stylesheet" href="../assets/css/style.css"> </head> <body> <?php include '../includes/navbar.php'; ?> <div class="container"> <h2>Login</h2> <?php if (!empty($errors)) { echo
'<div class="error">'; foreach
($errors as $error) {
echo "<p>$error</p>"; } echo
'</div>'; } ?> <form
action="login.php" method="POST"> <label
for="email">Email:</label> <input
type="email" name="email" required> <label
for="password">Password:</label> <input
type="password" name="password" required> <button
type="submit">Login</button> </form> <p>Don't have an account?
<a href="register.php">Register here</a>.</p> </div> <?php include '../includes/footer.php'; ?> </body> </html>
|
🔍
Code Explanation
1.
Database Connection
o require_once
'../database/db_config.php'; includes the database connection file.
2.
Session Handling
o session_start();
is used to store user session data upon successful login.
3.
Processing Form Submission (POST
Request)
o Retrieves
email and password from the form.
4.
Basic Input Validation
o Ensures
email and password are not empty.
o Checks
if the email format is valid.
5.
Fetching User Data from MySQL
Database
o Uses
mysqli_query() to fetch user details using the email.
o If
the email exists, it fetches user data using mysqli_fetch_assoc().
6.
Password Verification
o Compares
the entered password with the hashed password from the database using password_verify().
7.
Session Storage & User
Redirection
o If
authentication is successful, the user's details are stored in $_SESSION.
o The
user is redirected to either admin_dashboard.php or user_dashboard.php based on
their role.
8.
Error Handling
o Displays
appropriate error messages if login fails.
Output:
✅ Complete login.php Using prepared statement
<?php require_once '../database/db_config.php'; //
Database connection session_start(); if ($_SERVER["REQUEST_METHOD"] ==
"POST") { $email =
trim($_POST['email']); $password =
trim($_POST['password']); $errors = []; // Validate input fields if (empty($email) ||
empty($password)) { $errors[]
= "Email and Password are required!"; } // Validate email format if (!filter_var($email,
FILTER_VALIDATE_EMAIL)) { $errors[]
= "Invalid email format!"; } if (empty($errors)) { //
Prepare and execute the query securely $query
= "SELECT id, name, email, password, role FROM users WHERE email =
?"; $stmt
= mysqli_prepare($conn, $query); if
($stmt) { mysqli_stmt_bind_param($stmt,
"s", $email); mysqli_stmt_execute($stmt); $result
= mysqli_stmt_get_result($stmt); if
($row = mysqli_fetch_assoc($result)) { //
Verify password using password_verify() if
(password_verify($password, $row['password'])) { //
Store user data in session $_SESSION['user_id']
= $row['id']; $_SESSION['user_name']
= $row['name']; $_SESSION['user_email']
= $row['email']; $_SESSION['user_role']
= $row['role']; //
Redirect based on role if
($row['role'] === 'admin') { header("Location:
admin_dashboard.php"); }
else { header("Location:
user_dashboard.php"); } exit(); }
else { $errors[]
= "Incorrect password!"; } }
else { $errors[]
= "Email not found!"; } //
Close statement mysqli_stmt_close($stmt); }
else { $errors[]
= "Database error: Unable to prepare statement."; } } // Close database connection mysqli_close($conn); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta
charset="UTF-8"> <meta
name="viewport" content="width=device-width,
initial-scale=1.0"> <title>Login</title> <link
rel="stylesheet" href="../assets/css/style.css"> </head> <body> <?php include '../includes/navbar.php'; ?> <div class="container"> <h2>Login</h2> <?php if (!empty($errors)) { echo
'<div class="error">'; foreach
($errors as $error) { echo
"<p>$error</p>"; } echo
'</div>'; } ?> <form
action="login.php" method="POST"> <label
for="email">Email:</label> <input
type="email" name="email" required> <label
for="password">Password:</label> <input
type="password" name="password" required> <button
type="submit">Login</button> </form> <p>Don't have an
account? <a href="register.php">Register
here</a>.</p> </div> <?php include '../includes/footer.php'; ?> </body> </html>
|
🔍
Code Explanation
1.
Database Connection (db_config.php)
o require_once
'../database/db_config.php'; includes the database connection file.
o $conn
is assumed to be the MySQLi connection object.
2.
Session Handling
o session_start();
starts a session to store user details.
3.
Form Handling (POST Method)
o trim($_POST['email'])
& trim($_POST['password']) remove unnecessary spaces.
o If
either field is empty, an error message is added to $errors[].
o filter_var($email,
FILTER_VALIDATE_EMAIL) ensures valid email format.
4.
Database Query Using MySQLi Prepared
Statements
o A
prepared statement prevents SQL injection:
$stmt = mysqli_prepare($conn, $query);
mysqli_stmt_bind_param($stmt, "s", $email);
o If
the query is successful, it fetches the user details.
o password_verify($password,
$row['password']) checks if the hashed password matches the input.
5.
Session Variables & Redirection
o If
login is successful, user details are stored in $_SESSION.
o Redirects:
§ Admin
→ admin_dashboard.php
§ User
→ user_dashboard.php
6.
Displaying Errors (If Any)
o If
authentication fails (wrong password, invalid email, etc.), an error message
appears.
7.
Login Form
o Accepts
email and password inputs.
o Uses
the required attribute for form validation.
8.
Closing Database Connection
o mysqli_stmt_close($stmt);
closes the prepared statement.
o mysqli_close($conn);
closes the database connection.
3. logout.php
the logout.php file, which will
properly destroy the session and redirect the user to the login page.
✅ Complete
logout.php Code
<?php session_start(); // Destroy all session data session_unset(); session_destroy(); // Redirect to login page header("Location: login.php"); exit(); ?>
|
🔍 Code Explanation
1.
Start the session
o session_start();
ensures that the session is active before modifying it.
2.
Clear session variables
o session_unset();
removes all session variables.
o session_destroy();
completely destroys the session.
3.
Redirect the user to the login page
o header("Location:
login.php"); sends the user back to the login page.
o exit();
ensures that no further script execution occurs after redirection.