the login.php form and password.php is working but the validation for entering a site is not
code for "passwords.php"
<?php
$USERS["username1"] = "password1";
$USERS["username2"] = "password2";
$USERS["username3"] = "password3";
function check_logged(){
global $_SESSION, $USERS;
if (!array_key_exists($_SESSION["logged"],$USERS)) {
header("Location: login.php");
};
};
?>
login.php
<?php
session_start();
include("passwords.php");
if ($_POST["ac"]=="log") { /// do after login form is submitted
if ($USERS[$_POST["username"]]==$_POST["password"]) { /// check if submitted
$_SESSION["logged"]=$_POST["username"];
} else {
echo 'Incorrect username/password. Please, try again.';
};
};
if (array_key_exists($_SESSION["logged"],$USERS)) { //// check if user is logged or not
echo "You are logged in."; //// if user is logged show a message
} else { //// if not logged show login form
echo '<form action="login.php" method="post"><input type="hidden" name="ac" value="log"> ';
echo 'Username: <input type="text" name="username" />';
echo 'Password: <input type="password" name="password" />';
echo '<input type="submit" value="Login" />';
echo '</form>';
};
?>
i cant make this part work
validation for page:
<?php
session_start(); /// initialize session
include("passwords.php");
check_logged(); /// function checks if visitor is logged.
?>
page code goes here
what am i doing wrong? the validation does not check if the user is logged in or not. it just proceeds to the page.
You should add exit; after setting the redirection header so the rest of the page doesn't get processed.
if (!array_key_exists($_SESSION["logged"],$USERS)) {
header("Location: login.php");
exit;
};
Also, did you try closing the browser to clear all the session data and see if you are still logged in?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.