How to Create User login system in PHP
Here is an example of a simple HTML/PHP login form that uses PHP sessions to authenticate the user:
<html>
<head>
<title>Login</title>
</head>
<body>
<form action="login.php" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username">
<br>
<label for="password">Password:</label>
<input type="password" id="password" name="password">
<br>
<input type="submit" value="Login">
</form>
</body>
</html>
session_start();if(isset($_POST['username']) && isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
// Connect to the database and authenticate the user
// You should use prepared statements to prevent SQL injection
$db = new mysqli('localhost', 'db_user', 'db_password', 'db_name');
$result = $db->query("SELECT * FROM users WHERE username='$username' AND password='$password'");if($result->num_rows > 0) {
// The user is authenticated
$_SESSION['authenticated'] = true;
$_SESSION['username'] = $username;
header('Location: dashboard.php');
exit;
} else {
// The user is not authenticated
echo 'Invalid username or password';
}
}
In this example, the login form is a simple HTML form that submits the username and password to the login.php page via the POST method. The login.php page then retrieves the submitted username and password, connect to the database and authenticate the user by checking the username and password against the users table. If the user is authenticated, a session variable “authenticated” is set to true and the username is also set in session variable “username”. The user is then redirected to the dashboard page and the session is used to check if the user is authenticated on the dashboard page. It is important to note that, for security reasons, the user’s password should always be hashed and salted before storing in the database and the prepared statement should be used for avoiding SQL injection.