I have made a simple login form with session, but the session is not maintaining and it throws:
Notice: Undefined index: user in C:\\wamp\\www\\practice\\user.php on line 3 ERROR
Code
<?php session_start(); ?>
<html>
<head>
<title>Login</title>
</head>
<body>
<form action= "user.php" method="post">
<input type = "text" placeholder = "Enter your Name" name="user"/>
<input type ="submit" value ="Submit"/>
</form>
</bod>
</html>
User.php
<?php
session_start();
$_SESSION['user'] = $_POST['user'];
if (isset($_SESSION['user']))
{
echo "You are logged in as ".$_SESSION['user'];
}
else
{
echo "Please login ";
}
?>
update your code like this
if(isset($_POST['user']))
$_SESSION['user'] = $_POST['user'];
Update your code
<?php
session_start();
if(isset($_POST['user']) && $_POST('user')!="") {
$_SESSION['user'] = $_POST['user'];
}
if (isset($_SESSION['user'])){
echo "You are logged in as ".$_SESSION['user'];
}else {
echo "Please login ";
}
?>
The session_start()
function must appear first while trying to use session variables.
<?php
session_start();
if(isset($_POST['user'])) // check whether the user value is set; The error was because you missed to check whether the $_POST['user'] is set
{
$_SESSION['user'] = $_POST['user'];
echo "You are logged in as ".$_SESSION['user'];
}
else
{
echo "Please login ";
}
?>
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.