Question: how do i fix my cookie so it only lets me access hw1.php unless my login is correct. and if incorrect hw1.php cannot be accessed

how do i fix my cookie so it only lets me access hw1.php unless my login is correct. and if incorrect hw1.php cannot be accessed and redirects to hwlogin.php

hw1login.php

code:

// Connect to the database $conn = new mysqli('localhost', '', '', ''); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); }

// If the form has been submitted if ($_SERVER['REQUEST_METHOD'] == 'POST') { // Get the username and password from the form $username = $_POST['username']; $password = $_POST['password'];

// Prepare the SQL query to check if the user exists $stmt = $conn->prepare('SELECT id FROM user WHERE username = ? AND password = ?'); $stmt->bind_param('ss', $username, $password); $stmt->execute(); $stmt->store_result();

// If the user exists, set a cookie named "user" and redirect to the hw1.php page if ($stmt->num_rows > 0) { $stmt->bind_result($id); $stmt->fetch(); setcookie('userid', time() + (86400 * 30), "/"); header('Location: week6.php'); exit; } else { $error = 'Incorrect username or password'; } } ?>

Login

Login

hw1.php

code:

// Start the session

session_start();

// If the user is not logged in, redirect to the login page

if (!isset($_COOKIE['userid'])) {

header('Location: hwlogin.php');

exit;

}

?>

Protected Page

Welcome to the protected page

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!