What are some best practices for creating a login system in PHP for a community website?
Issue: Creating a secure login system in PHP for a community website is essential to protect user data and ensure only authorized users can access certain features. Code snippet:
<?php
session_start();
// Check if the form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Include database connection
require_once "db_connection.php";
// Get user input from the login form
$username = $_POST['username'];
$password = $_POST['password'];
// Sanitize user input
$username = mysqli_real_escape_string($conn, $username);
$password = mysqli_real_escape_string($conn, $password);
// Query the database for the user
$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = mysqli_query($conn, $query);
// Check if the user exists
if(mysqli_num_rows($result) == 1){
// User is authenticated, create session
$_SESSION['username'] = $username;
header("Location: dashboard.php");
} else {
// Invalid credentials, show error message
echo "Invalid username or password";
}
}
?>
Keywords
Related Questions
- What are some best practices for handling session variables in PHP to avoid errors like "headers already sent"?
- How can the array_diff function be utilized to remove unnecessary values from a database based on array comparisons in PHP?
- How can PHP developers ensure that data inputs and transmissions are encrypted when including files from different domains?