What are some common methods for implementing user authentication and registration in PHP?
User authentication and registration are common functionalities in web applications that require users to create accounts, log in, and access personalized content. To implement user authentication and registration in PHP, developers can use techniques such as storing user credentials securely in a database, using sessions to track user login status, and validating user input to prevent security vulnerabilities.
// User authentication and registration in PHP
// Database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
// User registration
$username = $_POST['username'];
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);
$sql = "INSERT INTO users (username, password) VALUES ('$username', '$password')";
$conn->query($sql);
// User authentication
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM users WHERE username='$username'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
if (password_verify($password, $row['password'])) {
// User authenticated, set session
session_start();
$_SESSION['username'] = $username;
echo "Login successful";
} else {
echo "Invalid username or password";
}
} else {
echo "User not found";
}
$conn->close();