1
votes

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 ";
    }
?>
3
You don't use isset on $_POST['user']. - h2ooooooo
Sidenote: I edited your question but not actual code. You have a typo in </bod> - Funk Forty Niner
undefined index occurs when the array element with the intended key is not present. when the page is first loaded $_POST['user'] is not set.Hence you are getting the notice. you should use isset(). - shanavascet

3 Answers

0
votes

update your code like this

if(isset($_POST['user']))
  $_SESSION['user'] = $_POST['user'];
0
votes

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 ";
    }
?>
0
votes

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 ";
}
?>