Muhammad Siyab
Muhammad Siyab

Reputation: 57

Storing users sessions

I have a login and signup page, actually i want to store users sessions when they click logout button,they are not allowed to enter the home page until they enter their user name and password..! On the login page i have the code for storing the session.

 $user_name = $_SESSION['user_name'] = $_POST['user_name'];

And on the home page i have the condition..

<?php
session_start();
if(!$_SESSION['user_name']==1){
    header("location:login.php?error=You must be logged in first!");
    exit();
}
?>

The main issue is that when user clicks logout and redirects to the login page ..if he type the home page URL in the addressbar..he reaches the home page without entering the passsword and login..What's the problem..

Upvotes: 0

Views: 56

Answers (1)

keziah
keziah

Reputation: 574

Try this

login.php

<?php
    session_start();

    // Log in on submit
    if (isset($_POST['user_name']) /* whatever */) {
        // Do some login validations here
        // and if successful, set the session then redirect
        $_SESSION['sess_user'] = $_POST['user_name'];
        header('Location: /members.php');
        exit();
    }
?>

logout.php

<?php
    session_start();

    // Unset all session values 
    $_SESSION = array();

    // get session parameters 
    $params = session_get_cookie_params();

    // Delete the actual cookie. 
    setcookie(session_name(), '', time() - 42000, $params['path'], $params['domain'], $params['secure'], $params['httponly']);

    // Destroy the session 
    session_destroy();

    header("Location: /login.php");
?>

members.php

<?php
    session_start();

    // Check if authenticated
    if (!isset($_SESSION['sess_user'])) {
        header("location:login.php?error=You must be logged in first!");
        exit();
    }
?>

Upvotes: 1

Related Questions