Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$_Session "complication" on login and logout php

I'm doing a database project for university and I'm strugling with a problem in here. I'm trying to show "log in" when there's no session and "log out" when there is a session. But actually even after I log in it still shows me "log in" and I tried to print_r($_SESSION); and it tells me that the variable is undefined

I have a logout file:

<?php
session_start();
session_destroy();
header("Location:index.php");
?>  

and a init.php file:

<?php
session_start();
?> 

init.php is called when I log in.

Here is a part of index.php:

<?php
    require 'db/connect.php';
    require 'functions/security.php';
    ?>

    <html>
        <head>
            <title>Home</title>
            <meta charset="UTF-8">
            <link rel="stylesheet" href="css/common.css">
        </head>
        <body>
            <div id="linking">      
    <?php
    //print_r($_SESSION);
    if (session_status() === PHP_SESSION_NONE) {
        ?>
                    <a href="login.php">Log In</a>           
                    <?php
                } else {
                    ?>
                    <a href="logout.php">Log Out</a>
                    <?php
                }
                ?>
                <a href="new_customer.php">Register</a>
                <a href="trips.php">Search for trips</a>
            </div>
            <hr>
            <section id="section">
like image 636
André Santos Avatar asked Oct 20 '22 17:10

André Santos


1 Answers

when your login is success on login page.

session_start();
$_SESSION['user_logged_in'] = true;

in your logout page

session_start();
unset($_SESSION['user_logged_in']);   
session_destroy();

in your home page

<?php 
   session_start();
   if(isset($_SESSION['user_logged_in'])) {
 ?>
   < a href='logout.php'>Logout</a>
<?php  
   }
else {
?>
    < a href='login.php'>Login</a>
<?php 
  }
 ?> 
like image 61
Tintu C Raju Avatar answered Oct 22 '22 13:10

Tintu C Raju