This is part of my index.php code, it prints the current users login $SESSION. But when the user clicks logout it gives an error message saying "Undefined index: username" on line x. What does this mean and how can I fix it?
<?php
$dbname = 'lw17894'; # Change to your username
$dbuser = 'lw17894';
$dbpass = 'obscure';
$dbhost = 'localhost';
$link = mysqli_connect( $dbhost, $dbuser, $dbpass )
or die( "Unable to Connect to '$dbhost'" );
mysqli_select_db( $link, $dbname )
or die("Could not open the db '$dbname'");
if($_SESSION['username']) {
echo "Welcome, User: {$_SESSION['username']}";
} else {
echo "User not logged in!";
}
?>
and heres my logout.php code:
<?php
session_start()
?>
<!DOCTYPE html>
<html>
<body>
<?php
session_unset();
session_destroy();
echo "<h1>You are logged out!</h1>";
echo "<br>";
echo "<h2><strong>You will be redirected back to Home in 3 seconds</strong></h2>";
?>
<meta http-equiv="refresh" content="3;URL=index.php" />
</body>
</html>
由于会话被破坏,请尝试在 if 语句中使用 isset($_SESSION) && isset($_SESSION['username']) 。
When the user isn't logged in you're still checking the session variable for a username key.
Check if there's a session, and that the user name key exists in the session like this.
$dbname = 'lw17894'; # Change to your username
$dbuser = 'lw17894';
$dbpass = 'obscure';
$dbhost = 'localhost';
$link = mysqli_connect( $dbhost, $dbuser, $dbpass )
or die( "Unable to Connect to '$dbhost'" );
mysqli_select_db( $link, $dbname )
or die("Could not open the db '$dbname'");
if (session_status() != PHP_SESSION_NONE) {
if(array_key_exists ('username' , $_SESSION ) {
echo "Welcome, User: {$_SESSION['username']}";
} else {
echo "User not 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.