0

I have a website where user can login and signup. I am able to do the both and even verify the log in user password, but I am not able to add a logout button to the website after the user logs in.

The below code has an error in index.php file:

 $user = $_SESSION['userId'] ;

It says in that line Undefined index: userId in. If I can make it work I will be able to have a logout button, so user can login/logout. What am I doing wrong here so it is unable to fetch the userId details and rather is undefined? I have looked on SO similar questions, but none helped. Any help is appreciated.

In my login.php I have defined the $_SESSION['userId']

 if(password_verify($password, $hashed_password)) {
                    $_SESSION['email'] = $email;
                    $_SESSION['name'] = $row['username'];
                    $_SESSION['userId'] = $row['id'];

I have posted rest of my code below.

index.php

<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', '1');
require "navigationbar.php";
?>

<html>
<head>
<link href="https://fonts.googleapis.com/css2?family=Dancing+Script&display=swap" rel="stylesheet">
    <link
      rel="stylesheet"
      href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
    />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
    <script src="https://use.fontawesome.com/releases/v5.0.8/js/all.js"></script>
    <link href="stylee.css" rel="stylesheet" />
    <link href="https://fonts.googleapis.com/css2?family=Raleway:wght@100&display=swap" rel="stylesheet">
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>


</head>
<body>
<?php

    $user = $_SESSION['name'] ; //it says undefined index name
if (isset($user )) {
    echo '<p>You are logged in</p>';
echo '<form action="logout.php" method="post">
<button type="submit" name="logout-submit">Logout</button>
</form>';              
    
    <link href="stylee.css" rel="stylesheet" />
    <form action="logoutbackend.php" method="post">
    <button type="submit" name="logout-submit" class="logout_button">Logout</button>
    </form>';
} else {
    echo '<p class="login-status">You are logged out!</p>';
    echo '<div class="login-container">
    <form action="./backend/loginbackend.php"  method="post">
    
    <div class="form-group row">
    <div class="col-sm-10">
        <h2>website</h2>
    </div>
    
    </div>
    
        <div class="form-group row">
            <div class="col-sm-10">
                <input type="username" class="form-control" name="username" placeholder="username">
            </div>
        </div>
    
        <div class="form-group row">
            <div class="col-sm-10" >
                <input type="password" class="form-control" name="password" placeholder="password">
            </div>
        </div>
    
    <div class="form-group row">
        <div class="col-sm-10">
            <button type="submit" class="btn btn-primary" name="login_submit">Log In</button>
        </div>
    </div>
    </form>
    <div class="form-group row">
        <div class="col-sm-10">
            
            <p>New to <span>ShowCo</span>?<a class="open-button" onclick="openForm()">Sign up</a> </p>
        </div>
    </div>
    
    <div class="form-popup" id="myForm">
        <form action="./backend/signupbackend.php" class="form-container" method="post">
        <div class="form-group row">
            <div class="col-sm-10" >
            <h1>Sign up</h1>
        </div>
    </div>
     
        <div class="form-group row">
            <div class="col-sm-10" >
                <input type="text" class="form-control" placeholder="Username" name="username" required>
           </div>
        </div>
    
       
    
         <div class="form-group row">
            <div class="col-sm-10" >
                <input type="email"class="form-control" placeholder="Email address" name="mail" required>
            </div>
        </div>
        <div class="form-group row">
            <div class="col-sm-10" >
                <input type="password" class="form-control" placeholder="Password" name="password" required>
            </div>
      </div>
    
         <div class="form-group row">
            <div class="col-sm-10" >
                <input type="password" class="form-control" placeholder="Repeat password" name="repeatpassword" required>
            </div>
        </div>  
        <div class="form-group row">
            <div class="col-sm-10" >
                <button type="submit" class="btn btn-primary" name="signup_submit">Sign up</button>
             </div>
        </div>
    
        
                <button type="button" class="close" aria-label="Close" onclick="closeForm()"><span aria-hidden="true">&times;</span></button>
           
        </form>
    </div>
    
    
    
    
    </div>
    
    <script>
    function openForm() {
        document.getElementById("myForm").style.display = "block";
    }
    function closeForm() {
        document.getElementById("myForm").style.display = "none";
    }
    
    </script>
    
';
}
?>

</body>


</html>


<?php
require "footer.php";
?>

Signupbackend.php

<?php 
if(isset($_POST["signup_submit"])) {
   
    require "../database_files/database_for_signup.php";
    require "../index.php";

    $username = $_POST['username'];
    $email = $_POST['mail'];
    $password = $_POST['password'];
    $repeatPassword = $_POST['repeatpassword'];

    if (empty($username) || empty($email) || empty($password) || empty($repeatPassword)) {
        header("Location: ../index.php?error=emptyfields&username=" .$username."&mail=" .$email);
        exit();
    } else if(!filter_var($email, FILTER_VALIDATE_EMAIL) && !preg_match("/^[a-zA-Z0-9]*$/",$username)) {
        header("Location: ../index.php?error=invalidmailusername");
       exit();
    } else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        header("Location: ../index.php?error=invalidmail&username=".$username);
        exit();
    } else if (!preg_match("/^[a-zA-Z0-9]*$/",$username)) {
        header("Location: ../index.php?error=invalidusername&mail=".$email);
        exit();
    } else if($password != $repeatPassword) {
        header("Location: ../index.php?error=passwordcheck&username=".$username."&mail=".$email);
        exit();
    } else {


        $sql = "SELECT COUNT(username) AS num FROM signup_info WHERE username = :username";
        $stmt = $conn->prepare($sql);

        $stmt->bindValue(':username', $username);
        $stmt->execute();
        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($row['num'] > 0) {
            die('Sorry, username already exists. Please try a different username');
        }

        $passwordHash = password_hash($password, PASSWORD_BCRYPT, array("cost" => 12));
        
        $sql = "INSERT INTO signup_info(username, email, password) VALUES (:username, :email, :password)";
        $stmt = $conn->prepare($sql);

        $stmt->bindValue(':username', $username);
        $stmt->bindValue(':email', $email);
        $stmt->bindValue(':password', $passwordHash);

        $result = $stmt->execute();

        if($result) {
            echo "Registered!";
        }

       
           
    }
}
           


?>

loginbackend.php

<?php
session_start();
if(isset($_POST['login_submit'])) {

    require "../database_files/database_for_signup.php";
   $username = $_POST['username'];
   $password = $_POST['password'];

   if ((empty($username)) || (empty($password))) {
       echo 'empty username/password';
       die();
   } 
  
$sql = 'SELECT username, email, password FROM signup_info WHERE username = :username';

if ($stmt = $conn->prepare($sql)) {
    $stmt->bindParam(':username', $username, PDO::PARAM_STR);
    if ($stmt->execute()) {
        if($stmt->rowCount() == 1) {
            if ($row = $stmt->fetch()) {
                $hashed_password = $row['password'];
                if(password_verify($password, $hashed_password)) {
                    $_SESSION['email'] = $email;
                    $_SESSION['name'] = $row['username'];
                    $_SESSION['userId'] = $row['id'];
                    echo "verfiied";
                } else {
                    echo "wrong password";                }
            }
        }
    }
}

  
   
}

?>

logout.php

<?php 

session_start();
unset($_SESSION['username']);
session_unset();
session_destroy();
header("Location: ./index.php");
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
  • You have insufficient error checking for when the user is logged out. E.g use `if (isset($_SESSION["user"]))` instead of `if (isset($user ))` – GetSet Sep 16 '20 at 05:13
  • @GetSet Thanks for letting me know. I have tried that as well before, but the error is still the same. –  Sep 16 '20 at 05:14
  • Highly doubt that. ..... Why? You make an assignment on a var to a session var that you never check if it exists – GetSet Sep 16 '20 at 05:16
  • @GetSet Sorry, I don't understand you well. I am saying what you mentioned in the comment I have tried that before, and even changed my code to that now `if (isset$_SESSION['userId']`). I still get the same error. Also, am I suppose to write `user` or `userId`. As you said to write `user` inside SESSION. –  Sep 16 '20 at 05:20
  • Well likely because you never removed this line `$user = $_SESSION['name'] ; //it says undefined index name` ..... Helps to check if the session var exists first – GetSet Sep 16 '20 at 05:22
  • The obvious case is why likely your question was closed. .... A link was provided for more insights – GetSet Sep 16 '20 at 05:23
  • @GetSet Yeah, the error disappeared. Sorry for not being able to understand you well. I did what you said and there is no error. I still can't see the logout button though. –  Sep 16 '20 at 05:25
  • @GetSet I have tried printing something inside the `if` statement, I assume it's not true and it goes to `else` statement. What am I doing wrong? –  Sep 16 '20 at 05:27
  • Ok, start a new question. Please include the link to this "closed" topic as reference. No answers can happen on this thread. But on a new thread, possibly. – GetSet Sep 16 '20 at 05:27
  • @GetSet Okay, I will do that. Shall I write all the code as well in new question if I provide the reference to old? Thanks. –  Sep 16 '20 at 05:27
  • If you want help, be verbose. But with code. Be succinct on problem in words best as you can – GetSet Sep 16 '20 at 05:30
  • @GetSet I can only post every 90 minutes, so I will post it soon when I can. Thanks. –  Sep 16 '20 at 05:36
  • I didnt know that – GetSet Sep 16 '20 at 05:37
  • @GetSet Unfortunately, it says so. –  Sep 16 '20 at 05:37
  • Gives you time to solve the problem – GetSet Sep 16 '20 at 05:38
  • @GetSet I assume the value is still undefined it's why it is not working –  Sep 16 '20 at 05:45
  • Isnt programming a bunch of `if` conditions? Open a new thread – GetSet Sep 16 '20 at 05:55
  • @GetSet https://stackoverflow.com/questions/63914487/logout-button-is-not-displaying –  Sep 16 '20 at 06:42
  • @GetSet I have posted a new question. Please have a look. –  Sep 16 '20 at 06:42

0 Answers0