What are the key components and steps involved in creating a functional website login/logout and registration script using PHP?
To create a functional website login/logout and registration script using PHP, you will need to have a database to store user information, create HTML forms for registration and login, validate user input, and handle sessions to keep track of logged-in users.
<?php
session_start();
// Database connection
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
// Registration script
if(isset($_POST['register'])){
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "INSERT INTO users (username, password) VALUES ('$username', '$password')";
$conn->query($sql);
}
// Login script
if(isset($_POST['login'])){
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = $conn->query($sql);
if($result->num_rows > 0){
$_SESSION['username'] = $username;
header("Location: dashboard.php");
} else {
echo "Invalid username or password";
}
}
// Logout script
if(isset($_POST['logout'])){
session_destroy();
header("Location: index.php");
}
?>