What are the best practices for implementing a login system in PHP?
Implementing a secure login system in PHP involves hashing passwords, using prepared statements to prevent SQL injection, and setting up session management for authenticated users.
<?php
// Start session
session_start();
// Check if the form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Validate input data
$username = $_POST['username'];
$password = $_POST['password'];
// Hash the password
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
// Check if the username and password match in the database
// Use prepared statements to prevent SQL injection
// If login is successful, set session variables
$_SESSION['username'] = $username;
$_SESSION['loggedin'] = true;
// Redirect to the dashboard or homepage
header("Location: dashboard.php");
exit();
}
?>
Related Questions
- How can PHP developers prevent special characters like quotes and commas from being treated as PHP commands in text fields?
- What are the best practices for handling database queries within a PHP script to avoid errors like "Invalid argument supplied for foreach()"?
- What are the limitations of using PHP datetime picker for older browsers like IE 4?