How can PHP be used to protect an HTML script with a password and handle user login sessions?
To protect an HTML script with a password and handle user login sessions in PHP, you can create a login form where users enter their credentials. Upon submission, the PHP script will verify the credentials and set a session variable to keep the user logged in. You can then check this session variable on protected HTML pages to restrict access.
<?php
session_start();
$valid_username = "username";
$valid_password = "password";
if(isset($_POST['username']) && isset($_POST['password'])){
if($_POST['username'] == $valid_username && $_POST['password'] == $valid_password){
$_SESSION['loggedin'] = true;
} else {
echo "Invalid username or password";
}
}
if(isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true){
// HTML content here
} else {
echo "Please login to access this page";
}
?>
Related questions
-
array_filter array_map PHP
-
getimagesize file paths PHP
-
Payment gateway integration PHP programming e-commerce website