What are some best practices for creating a login form in PHP?
When creating a login form in PHP, it is important to follow best practices to ensure the security of user credentials. One key practice is to hash user passwords before storing them in the database to prevent unauthorized access. Additionally, use prepared statements to prevent SQL injection attacks and validate user input to prevent cross-site scripting attacks.
<?php
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Process login form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST['username'];
$password = $_POST['password'];
// Hash the password
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
// Prepare SQL statement
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_assoc();
if ($user && password_verify($password, $user['password'])) {
// Login successful
echo "Login successful!";
} else {
// Login failed
echo "Invalid username or password";
}
$stmt->close();
}
$conn->close();
?>