I'm new at programming and I'm working with some PHP. I was given a file called login.php
and some directions to create a second file called admin.php
.
Here are the instructions.
admin.php
If the user tries to access this file without logging in, re-direct them back to the login.php page which should display a message saying “Invalid Login” – use the session variable to check.
If they are logged in:
provide them with the value of the “loggedIn” cookie with the message: “You logged in January 25, 10:00am” (or whatever the value is)
unset the session variable and destroy the session and
unset both cookies (session and ‘loggedIn’) and set to expire so it will be removed by the browser.
NOTE: test the already logged in portion of login.php before adding the code to destroy the session and the cookie.
Once you’ve got the above working, change your code so that if they are redirected to login.php from admin.php, it should display a different message: “You need to log in”.
<?php
session_start();
$message = null;
if (isset($_SESSION['loggedIn']) && $_SESSION['loggedIn'] == 'true') {
header("Location: admin.php");
exit();
}
if ( $_SERVER['REQUEST_METHOD'] == 'GET') {
if ( sizeof($_GET) && isset($_GET['username']) && isset($_GET['password']) && $_GET['username'] && $_GET['password']) {
if ($_GET['username'] == 'username' && $_GET['password'] == 'password') {
$_SESSION['loggedIn'] = 'true';
setcookie ("loggedIn", date("F d,Y h:ia"), time()+60*10, "/", $_SERVER['SERVER_NAME']);
header("Location: admin.php");
exit();
} else {
$message = 'Invalid Login';
}
} else {
$message = 'Invalid Login';
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Login</title>
</head>
<body>
<?php if($message) echo '<div class="warning">' . $message . '</div>'; ?>
<form method="get">
<label for="username">Username</label>
<input type="text" name="username" id="username" value="username" />
<label for="password">Password</label>
<input type="password" name="password" id="password" value="password" />
<input type="submit" name="submit" value="Login" />
</form>
</body>
</html>
The code below is all I have so far. I want to know if my unsetting is correct with the session variables and cookies. Also, how do I display the date and time as stated in the instructions, and how do I display a message of "You need to log in if the user is directed to the login.php page from the admin.php page?
<?php
session_start();
if (!isset($_SESSION['loggedIn']) && $_SESSION['loggedIn'] == 'false') {
header("Location: login.php");
exit();
} else {
unset($_SESSION['loggedIn']);
session_unset();
session_destroy();
unset($_COOKIE['loggedIn']);
}
?>