Introduction:
Learn how to create a robust web application with user authentication and a to-do list feature using PHP and MySQL. This comprehensive tutorial guides you through setting up a local development environment with XAMPP, creating a user registration system, implementing secure login functionality, and building a simple to-do list application. Enhance your PHP and MySQL skills while understanding the fundamentals of web security.
User authentication in a web application using XAMPP and MySQL typically involves creating a user database, implementing registration and login functionality, and securing access to certain parts of your website.
Install XAMPP on your local machine if you haven’t already.
3.Create a table within the database to store user information, such as users.
Define columns like :
id (auto-increment), username, email, and password.
Create an HTML form for user registration.
<!-- register.php --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>User Registration</title> </head> <body> <h2>Register</h2> <form action="register_process.php" method="post"> <label for="username">Username:</label> <input type="text" name="username" required><br> <label for="email">Email:</label> <input type="email" name="email" required><br> <label for="password">Password:</label> <input type="password" name="password" required><br> <button type="submit">Register</button> </form> </body> </html>
Connect to the MySQL database and insert user details.
<!-- register_process.php --> <?php $servername = "localhost"; $username = "root"; $password = ""; $dbname = "user_auth"; $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } if ($_SERVER["REQUEST_METHOD"] == "POST") { $username = $_POST["username"]; $email = $_POST["email"]; $password = password_hash($_POST["password"], PASSWORD_DEFAULT); $sql = "INSERT INTO users (username, email, password) VALUES ('$username', '$email', '$password')"; if ($conn->query($sql) === TRUE) { echo "Registration successful"; } else { echo "Error: " . $sql . "<br>" . $conn->error; } } $conn->close(); ?>
Create an HTML form for user login.
<!-- login.php --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>User Login</title> </head> <body> <h2>Login</h2> <form action="login_process.php" method="post"> <label for="username">Username:</label> <input type="text" name="username" required><br> <label for="password">Password:</label> <input type="password" name="password" required><br> <button type="submit">Login</button> </form> </body> </html>
Connect to the MySQL database, verify user credentials, and set a session.
<!-- login_process.php --> <?php session_start(); $servername = "localhost"; $username = "root"; $password = ""; $dbname = "user_auth"; $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } if ($_SERVER["REQUEST_METHOD"] == "POST") { $username = $_POST["username"]; $password = $_POST["password"]; $sql = "SELECT id, username, password FROM users WHERE username='$username'"; $result = $conn->query($sql); if ($result->num_rows > 0) { $row = $result->fetch_assoc(); if (password_verify($password, $row["password"])) { $_SESSION["user_id"] = $row["id"]; echo "Login successful"; } else { echo "Invalid password"; } } else { echo "User not found"; } } $conn->close(); ?>
Check if the user is authenticated before displaying the page content.
<!-- protected.php --> <?php session_start(); if (!isset($_SESSION["user_id"])) { header("Location: login.php"); exit(); } echo "Welcome to the protected page, user!"; ?>
Now, we have a basic user authentication system. Users can register, login, and access the protected page after authentication.
Note that this example does not cover important security considerations such as SQL injection prevention, CSRF protection, and secure password practices, which should be implemented in a production environment.
Install XAMPP on your local machine if you haven’t already.
Create an HTML form for user registration.
<!-- register.php --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>User Registration</title> </head> <body> <h2>Register</h2> <form action="register_process.php" method="post"> <label for="username">Username:</label> <input type="text" name="username" required><br> <label for="email">Email:</label> <input type="email" name="email" required><br> <label for="password">Password:</label> <input type="password" name="password" required><br> <button type="submit">Register</button> </form> </body> </html>
Connect to the MySQL database and insert user details.
<!-- register_process.php --> <?php $servername = "localhost"; $username = "root"; $password = ""; $dbname = "todo_app"; $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } if ($_SERVER["REQUEST_METHOD"] == "POST") { $username = $_POST["username"]; $email = $_POST["email"]; $password = password_hash($_POST["password"], PASSWORD_DEFAULT); $sql = "INSERT INTO users (username, email, password) VALUES ('$username', '$email', '$password')"; if ($conn->query($sql) === TRUE) { echo "Registration successful"; } else { echo "Error: " . $sql . "<br>" . $conn->error; } } $conn->close(); ?>
Create an HTML form for user login.
<!-- login.php --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>User Login</title> </head> <body> <h2>Login</h2> <form action="login_process.php" method="post"> <label for="username">Username:</label> <input type="text" name="username" required><br> <label for="password">Password:</label> <input type="password" name="password" required><br> <button type="submit">Login</button> </form> </body> </html>
Connect to the MySQL database, verify user credentials, and set a session.
<!-- login_process.php --> <?php session_start(); $servername = "localhost"; $username = "root"; $password = ""; $dbname = "todo_app"; $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } if ($_SERVER["REQUEST_METHOD"] == "POST") { $username = $_POST["username"]; $password = $_POST["password"]; $sql = "SELECT id, username, password FROM users WHERE username='$username'"; $result = $conn->query($sql); if ($result->num_rows > 0) { $row = $result->fetch_assoc(); if (password_verify($password, $row["password"])) { $_SESSION["user_id"] = $row["id"]; echo "Login successful"; } else { echo "Invalid password"; } } else { echo "User not found"; } } $conn->close(); ?>
Create a page where users can view and manage their tasks.
<!-- tasks.php --> <?php session_start(); if (!isset($_SESSION["user_id"])) { header("Location: login.php"); exit(); } $servername = "localhost"; $username = "root"; $password = ""; $dbname = "todo_app"; $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $user_id = $_SESSION["user_id"]; // Fetch user's tasks from the database $sql = "SELECT * FROM tasks WHERE user_id='$user_id'"; $result = $conn->query($sql); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Task List</title> </head> <body> <h2>Your Tasks</h2> <ul> <?php while ($row = $result->fetch_assoc()) { echo "<li>{$row['task_description']}</li>"; } ?> </ul> <form action="add_task.php" method="post"> <label for="task">Add Task:</label> <input type="text" name="task" required> <button type="submit">Add</button> </form> <a href="logout.php">Logout</a> </body> </html>
Process the form submission to add a new task.
<!-- add_task.php --> <?php session_start(); if (!isset($_SESSION["user_id"])) { header("Location: login.php"); exit(); } $servername = "localhost"; $username = "root"; $password = ""; $dbname = "todo_app"; $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $user_id = $_SESSION["user_id"]; $task_description = $_POST["task"]; // Insert new task into the database $sql = "INSERT INTO tasks (user_id, task_description, created_at) VALUES ('$user_id', '$task_description', NOW())"; if ($conn->query($sql) === TRUE) { header("Location: tasks.php"); } else { echo "Error: " . $sql . "<br>" . $conn->error; } $conn->close(); ?>
Clear the session and redirect to the login page.
<!-- logout.php --> <?php session_start(); session_unset(); session_destroy(); header("Location: login.php"); exit(); ?>
This example creates a simple to-do list application where users can register, log in, add tasks, and view their tasks. As with any real-world application, consider implementing additional security measures, such as input validation, using prepared statements to prevent SQL injection, and protecting against CSRF attacks.
To run the application, follow these steps:
Set Up XAMPP:
If you haven’t already, download and install XAMPP from the official website.
Start the Apache and MySQL services from the XAMPP Control Panel.
Create the Database:
Open your web browser and go to http://localhost/phpmyadmin/.
Create a new database named todo_app.
Inside the todo_app database, create two tables: users and tasks with the specified columns.
Place Files in the XAMPP Root Directory:
Copy the PHP files (register.php, register_process.php, login.php, login_process.php, tasks.php, add_task.php, logout.php) into the XAMPP web server root directory. This is typically the htdocs folder inside the XAMPP installation directory.
Open your web browser and go to http://localhost/register.php to register a new user.
After registration, go to http://localhost/login.php to log in with the registered credentials.
Upon successful login, you will be redirected to http://localhost/tasks.php where you can view and manage tasks.
To logout, click on the “Logout” link on the tasks page. This will clear the session and redirect you to the login page.
Note:
Make sure your MySQL and Apache services are running in the XAMPP Control Panel.
Adjust the database connection settings in the PHP files if your MySQL server has a different configuration (username, password, database name).
The examples provided are for learning purposes and may lack some security measures. In a production environment, additional security considerations should be taken into account.
By following these steps, you should be able to run the basic to-do list application on your local machine using XAMPP and MySQL.
Here’s a quiz related to the lesson on creating a basic user authentication system and a to-do list application using PHP and MySQL. Each question is followed by an explanation.
A. To provide a text editor
B. To simulate a web server environment on a local machine
C. To encrypt user passwords
D. To create database tables
Explanation: B. XAMPP is a package that includes Apache (web server), MySQL (database server), PHP, and other tools. It allows you to simulate a web server environment on your local machine for testing and development.
A. http://localhost/phpmyadmin/
B. http://localhost/admin/
C. http://localhost/database/
D. http://localhost/mysql/
Explanation: A. phpMyAdmin is typically accessible at http://localhost/phpmyadmin/ in a XAMPP environment.
A. register.php
B. login.php
C. register_process.php
D. login_process.php
Explanation: C. The register_process.php file is responsible for connecting to the database and defining the structure of the user table by executing SQL queries.
A. To generate a random password
B. To hash user passwords for secure storage
C. To decrypt passwords
D. To check if a password is valid
Explanation: B. The password_hash function is used to securely hash passwords before storing them in the database.
A. In the HTML file
B. In the CSS file
C. In the PHP file handling the protected page
D. In the JavaScript file
Explanation: C. The check for user authentication should be performed in the PHP file handling the protected page, before rendering the content.
A. session_destroy()
B. session_start()
C. session_unset()
D. session_logout()
Explanation: A. The session_destroy() function is used to destroy all session data, effectively logging out the user.
A. To get the current time in PHP
B. To insert the current time into a MySQL database
C. To check if a user is online
D. To calculate the time difference between two dates
Explanation: B. The NOW() function in MySQL is used to insert the current date and time into a database column.
A. In the htdocs directory
B. In the bin directory
C. In the phpmyadmin directory
D. In the mysql directory
Explanation: A. In a XAMPP environment, PHP files should be placed in the htdocs directory to be accessible through a web browser.
A. To send an HTTP header to the browser
B. To redirect the user to another page
C. To set a cookie
D. To include an external script
Explanation: B. The header(“Location: …”) function is used to redirect the user to another page.
A. password_hash
B. password_verify
C. password_retrieve
D. password_fetch
Explanation: B. The password_verify function is used to compare a plain text password with its hashed version retrieved from the database.
A. Cross-Site Request Forgery; to prevent unauthorized actions on behalf of the user
B. Cross-Site Scripting; to protect against injection attacks
C. Cross-Origin Resource Sharing; to allow sharing of resources between domains
D. Cryptographic Secure File Requests; to encrypt file transfers
Explanation: A. CSRF stands for Cross-Site Request Forgery. It’s important to prevent it to avoid unauthorized actions performed on behalf of a user without their consent.
A. Cross-Site Scripting (XSS)
B. Cross-Site Request Forgery (CSRF)
C. SQL Injection
D. Brute Force Attack
Explanation: D. Password hashing helps mitigate brute force attacks by making it computationally expensive to guess passwords.
A. add_task.php
B. tasks.php
C. login_process.php
D. register_process.php
Explanation: A. In the add_task.php file, you should check if the user is authenticated before allowing them to add a new task.
A. To escape special characters in a SQL query
B. To encrypt passwords
C. To sanitize user input for display
D. To decode base64-encoded data
Explanation: A. The mysqli_real_escape_string function is used to escape special characters in a SQL query, helping to prevent SQL injection attacks.
A. To make the code shorter
B. To improve code readability
C. To prevent security vulnerabilities such as SQL injection and XSS attacks
D. To increase server performance
Explanation: C. Validating and sanitizing user input is crucial to prevent security vulnerabilities such as SQL injection and Cross-Site Scripting (XSS) attacks. It helps ensure the integrity and security of the application.