We help IT Professionals succeed at work.
Get Started

Loosing Session

APD Toronto
APD Toronto asked
Last Modified: 2015-02-26
Hi Experts,

I am starting a new application and trying to check if the user is logged in before letting them view the page. The exception to this is of course if they are on the login page..I have many files, includes, and I am using MVC, but I will try to post here wjat is relevant

Login form:
$page_title = 'Welcome, Please Login...';
$isLoginPage = TRUE;
require_once 'utilities/general_includes.php'; //General-purpose includes.

$error = '';
$message = '';

if (isset($_GET['type'])){
    if ($_GET['type'] == 'err') $error = $_GET['msg'];
    else $message = $_GET['msg'];


    <form name="frm" id="frm" autocomplete="off" method="post" action="login/?action=login"
              onSubmit="return checkRequired();">
            <label for="txtUser" class="required" >User Name:</label>
            <input type="text" name="txtUser" id="txtUser" class="required"><br><br>
            <label for="txtPassword" class="required">Password:</label>
            <input type="password" name="txtPassword" id="txtPassword" 
                   maxlength="255" class="required"><br><br> 
            <input type="submit" id="btnLogin" value="Login" class="button">

    <!--Place where appropriate-->
    <?php require_once 'utilities/messages.php'; ?> 

<script type="text/javascript">
    function checkRequired(){
        var uid = frm.txtUser.value;
        var pwd = frm.txtPassword.value;
        if ((uid === '') || (pwd === '')) {
            alert ('All fields are mandatory.');
            return false;
        return true;

Open in new window

//This include file includes all general-purpose includes.

if (!isset($isLoginPage)){
    $isLoginPage = FALSE;

require_once 'configuration.php';
require_once 'checkSecurity.php';
require_once 'database.php';
require_once 'page_setup.php';

Open in new window

login/index.php (Controller)

//This is the controller file for the current module.

require_once 'login.php';

$action = 'list'; //<-DEFAULT ACTION

//Get Action

if (isset($_GET['action'])){
    $action = $_GET['action'];
else if (isset($_POST['action'])){
    $action = $_POST['action'];

if ($action == 'login') {
    $isLoginPage = 1;

require_once '../utilities/general_includes.php'; //General-purpose includes.

$error = '';
$message = '';
        echo '<br> from login isLogin = '. $isLoginPage;
        echo '<br> from login sess = ' . $_SESSION['sess_id'];
switch ($action){
    case 'login':
        $user = $_POST['txtUser'];
        $password = $_POST['txtPassword'];
        $login_status = Login::verify_login($user, $password);
        if ($login_status == 'admin') {
            header('Location: index.php?action=list');
        else if ($login_status == 'rs') {
            header('Location: ../dispatch');
        else if ($login_status == 'no_cookies') {
            header('Location: ../?type=err&msg=Cookies must be enabled in your browser');
        else {
            header('Location: ../?type=err&msg=User Id / Password combination not found.');
    case 'logout':
        header('Location: ../?type=info&msg=Session successfully ended.');
    case 'list':

        $users = Login::get_login_list();
        $page_title = 'User List';
        $message = 'Select a user to change their password.';        
        include 'view_list.php';
    case 'pw_change':
        $uid = $_GET['user'];
        $user = Login::get_login($uid);
        $uid = $user['user'];
        $pwSha = $user['password'];
        $page_title = 'Change Login Password';
        include 'view_password-change.php';
    case 'pw_save':
        $uid = $_POST['txtUser'];
        $pwOld = $_POST['txtPWold'];
        $pwSha = $_POST['hidPWold'];
        $pwNew = $_POST['txtPWnew1'];
        if (sha1($pwOld) != $pwSha) {
            $error = 'Old Password does not match database. <br> <br>'
                    . 'Please try again.';
            $page_title = 'Change Login Password';
            include 'view_password-change.php';

            Login::set_password($uid, $pwNew);
            $message = 'Password Successfully Changed.';
           $users = Login::get_login_list();
           include 'view_list.php';
    case 'pw_cancel':
        $users = Login::get_login_list();
        $message = 'Password change cancelled.';
        include 'view_list.php';

Open in new window

login/login.php (Model)
<?php //This is the model file for the current module.

class Login {
    public static function verify_login($login_user, $password){
        //destroy previous session
        $user = self::get_login($login_user);
        if (count($user) == 0) return 'no_user';
        if (sha1($password) != $user['password']) return 'wrong password';
        //login success, start session
        global $env;
        $lifetime = 60 * 60 * 24; // 24h in seconds
        session_set_cookie_params($lifetime, '/', $env['domain'], TRUE, FALSE);
        if (session_start() == FALSE) return 'no_cookies';

        $_SESSION['sess_id'] = session_id();
        echo 'login sess = ' . $_SESSION['sess_id'];
        if (($login_user == 'reservations') || ($login_user == 'aleks')) {
            return 'rs';
        else {
            return 'admin';
    public static function logout() {

        //Destroy Session
        $_SESSION = array();
        if (isset($_SESSION['sess_id'])) session_destroy();

        //Delete Sess cookie
        $name = session_name();
        $expire = strtotime('-1 year');
        $params = session_get_cookie_params();
        $path = $params['path'];
        $domain = $params['domain'];
        $secure = $params['secure'];
        $httponly = $params['httponly'];

        setcookie($name, '', $expire, $path, $domain, $secure, $httponly);


    public static function get_login($user){
        $db = Database::getDB();
        $query = 'SELECT * FROM logins '
               . 'WHERE user = :user';
        $statement = $db->prepare($query);
            $statement->bindValue(':user', $user);
        $result = $statement->fetch();
        return $result;       

    public static function get_login_list() {
        $db = Database::getDB();
        $query = 'SELECT login_id, user FROM logins '
                . 'WHERE show_user = 1 '
                . 'ORDER By user';
        $statement = $db->prepare($query);
        $result = $statement->fetchAll();
        return $result;
    public static function set_password($user, $newPassword){
        $db = Database::getDB();
        $newPassword = sha1($newPassword);
        $query = 'UPDATE logins '
               . 'SET password = :pw '
               . 'WHERE user = :user'; 
          $statement = $db->prepare($query);
            $statement->bindValue(':pw', $newPassword);
            $statement->bindValue(':user', $user);

Open in new window

Finally, utilities/checkSecurity.php

    //go to SSL (IIS and Linux)    
    if (($_SERVER['HTTPS'] == 'off') || (!isset($_SERVER['HTTPS']))) {
        $url = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        header("Location: " . $url);
//Login Check
echo '<br> check sec sess = ' . $_SESSION['sess_id']; 
echo '<br> isLoginPage = ' . ($isLoginPage == TRUE);
    if ($isLoginPage == FALSE) {
        if (!isset($_SESSION['sess_id']) || ($_SESSION['sess_id'] == '')){
            echo '<br><br>not logged in';
            /*header('Location:' . $env['url'] . '/?type=err&msg=Must Login First.');
    //Referrer Check
        $referrer = $_SERVER['HTTP_REFERER'];
        $protocol_pos = strpos($referrer, '://') + 3;
        $ref_domain = substr($referrer, $protocol_pos);
        $domain_end = strpos($ref_domain, '/');
        $ref_domain = substr($ref_domain, 0, $domain_end);
        if ($ref_domain != $env['domain']){
            header('Location:' . $env['url'] . '/?type=err&msg=Referrer Check Failed.');

Open in new window

The problem is even after successful login, even when I get to the url ...//login/index.php?action=list I get the following output:

Notice: Undefined index: sess_id in C:\inetpub\wwwroot\CSS_Reservations\utilities\checkSecurity.php on line 10

check sec sess =
isLoginPage =

not logged in
from login isLogin =
Notice: Undefined index: sess_id in C:\inetpub\wwwroot\CSS_Reservations\login\index.php on line 28

from login sess =

from login sess = is coming from my Controller after I successfully login.

I know this is a lot, but when I break it down it works, but its some logical error that I cannot figure out.

My only suspicion is that I am using session_start(); a part of my general_includes.php, but on the other hand I feel that ok.

I have been at this whole day, so any help will be greatly appreciated.
Watch Question
Fixer of Problems
Most Valuable Expert 2014
This problem has been solved!
Unlock 2 Answers and 10 Comments.
See Answers
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE