In web development, user login and logout are one of the most basic and important functions. This article will use a simple example to explain in detail how to use PHP functions to implement a complete user login and logout process.
First, a database needs to be created to save the user's username and password. Here is an example SQL code for creating databases and data tables:
CREATE DATABASE user_info; USE user_info; CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, username VARCHAR(255) NOT NULL, password VARCHAR(255) NOT NULL );
Next, a login form page is needed to collect the account number and password entered by the user.
<!DOCTYPE html> <html> <head> <title>Login</title> </head> <body> <h1>Login</h1> <form action="login.php" method="POST"> <label for="username">Username:</label> <input type="text" name="username" id="username" required><br> <label for="password">Password:</label> <input type="password" name="password" id="password" required><br> <input type="submit" value="Login"> </form> </body> </html>
After the user submits the form, it will jump to the login processing page. This page will verify the account password and enable Session.
<?php session_start(); // Get form data $username = $_POST['username']; $password = $_POST['password']; // Connect to the database $mysqli = new mysqli('localhost', 'username', 'password', 'user_info'); // Query user information $query = "SELECT * FROM users WHERE username='$username' AND password='$password'"; $result = $mysqli-> query($query); //Judge login status if ($result->num_rows == 1) { $_SESSION['username'] = $username; header('Location: welcome.php'); } else { echo 'Invalid username or password.'; } ?>
After logging in successfully, jump to the welcome page. If you are not logged in, you will automatically redirect back to the login page.
<?php session_start(); if (isset($_SESSION['username'])) { $username = $_SESSION['username']; echo "Welcome, $username! "; echo '<a href="logout.php"> Logout '; } else { header('Location: login.php'); } ?>
After the user clicks to log out, the Session should be cleared and redirected back to the login page.
<?php session_start(); session_unset(); session_destroy(); header('Location: login.php'); ?>
Through PHP combined with MySQL database, a simple user login and logout function can be quickly implemented. It is recommended to encrypt and store passwords in actual projects (such as using password_hash() ), add verification code functions, and use prepared statements to prevent SQL injection to enhance system security.