session_start issue

Hi all,

I’ve been testing out a system on my local webserver and everything was working fine, all functions/scripts worked as they should. I’ve just uploaded this to a webserver and for some reason the session check script I wrote doesnt work and I cannot work out why???

On each page I check to see if the user is logged in and if not they are directed to the login page;-
[php]<?php
include(‘mysqli_connect.php’);
session_start();
$user_check=$_SESSION[‘login_user’];

$ses_sql=mysqli_query($db,"select username, level, id, client_id from fms_tbl_users where username=’$user_check’ ");

$row=mysqli_fetch_array($ses_sql,MYSQLI_ASSOC);

$login_session =$row[‘username’];
$login_level =$row[‘level’];
$login_id =$row[‘id’];
$login_client_id =$row[‘client_id’];

if(!isset($login_session))
{
header(“Location: …/login/”);
}
else
mysqli_query($db,“UPDATE fms_tbl_users SET LastTimeSeen = NOW() WHERE id = $login_id”);

?>[/php]

I have a similar script on my login page but they do not seem to be working.

My servers details are;-

Web hosted:
Apache/2.2.16 (Debian)
Database client version: libmysql - 5.1.66
PHP extension: mysqli Documentation

Local:
Microsoft-IIS/8.5
Database client version: libmysql - mysqlnd 5.0.8-dev - 20102224 -
PHP extension: mysqli Documentation

Any is appreciated as this script allows access to all my pages!!! thanks

First turn on error reporting if you already haven’t:
[php]/* Turn on error reporting */
ini_set(‘display_errors’, 1);
ini_set(‘display_startup_errors’, 1);
error_reporting(-1);[/php]

Second have you setup your database table on the remote server? This is common problem for me, for I tend to get everything working on my local server and forget about my remote server.

Third, if you have your remote database table setup, check the capitalization. This has caused me problems in the past, where it would work fine on the local server because it doesn’t care about capitalization and wouldn’t work on the remote sever because it does.

Hi Strider64

Thanks again for your help in sorting my php issues out. I’d set the database up already but your error report code did the trick - I have several issues, some I have sorted already where it was a dead link. The main issue is I am getting the following error and the session script isnt doing its job - at the minute all the pages are accessible regardless of permissions.

Warning: Cannot modify header information - headers already sent by (output started at /customers/6/4/8/httpd.www/fms/include/session_check.php:1) in /customers/6/4/8/httpd.www/fms/include/session_check.php on line 25

[font=arial]

[/font]

My current session check code is;-
[php]<?php
session_start();
$user_check=$_SESSION[‘login_user’];

include(‘mysqli_connect.php’);

/* Turn on error reporting */
ini_set(‘display_errors’, 1);
ini_set(‘display_startup_errors’, 1);
error_reporting(-1);

$ses_sql=mysqli_query($db,"select username, level, id, client_id from fms_tbl_users where username=’$user_check’ ");

$row=mysqli_fetch_array($ses_sql,MYSQLI_ASSOC);

$login_session =$row[‘username’];
$login_level =$row[‘level’];
$login_id =$row[‘id’];
$login_client_id =$row[‘client_id’];

if(!isset($login_session))
{
header(“Location: login/”);
}
else
mysqli_query($db,“UPDATE fms_tbl_users SET LastTimeSeen = NOW() WHERE id = $login_id”);

?>[/php]

Even if $login_session is NULL it is still set and that is the reason I believe you are getting that error; However, I’m not 100 percent positive. What I would do if I were you would to do this (if I’m following your logic correctly).

[php]if (!$row) {
// redirect with header(“Location: …”);
}[/php]

though I think logically it’s better to think true and than false for I think it’s easier to understand, for example
[php]if ($row) {
$_SESSION[‘user’][‘username’] = $row[‘username’];
// Set session variables…
} else {
header(“Location: GetMeOutofHere.php”);
exit();
}[/php]
You know $row is either going to be true (1) or false (0).

also this doesn’t look right:
[php]header(“Location: …/login/”);[/php]

usually it’s something like
[php]header(“Location: …/login/login.php”);
exit();[/php]
but I could be wrong.

I was looking at your code and I would do something like this

[php]$_SESSION[‘user’][‘username’] = $row[‘username’];
$_SESSION[‘user’][‘level’] = $row[‘level’];
$_SESSION[‘user’][‘id’] = $row[‘id’];
$_SESSION[‘user’][‘client_id’] = $row[‘client_id’];[/php]

that way in your config.php or utilities.inc.php you can do something like the following (I think):
[php]$user = isset($_SESSION[‘user’]) ? $_SESSION[‘user’] : NULL;[/php]

Though I’m not to sure for I’m more comfortable using objects than I’m using arrays, but I’m sure you could figure it out.

My guess, this file: include(‘mysqli_connect.php’); is outputting something.

thanks guys, I’m still working on this. The pages still load but I have the following error;-

Warning: Cannot modify header information - headers already sent by (output started at /customers/6/4/8/httpd.www/fms/include/session_check.php:1) in /customers/6/4/8/httpd.www/fms/include/session_check.php on line 22

my code is:-
[php]<?php
include(‘mysqli_connect.php’);
session_start();
$user_check=$_SESSION[‘login_user’];

/* Turn on error reporting */
ini_set(‘display_errors’, 1);
ini_set(‘display_startup_errors’, 1);
error_reporting(-1);

$ses_sql=mysqli_query($db,"select username, level, id, client_id from fms_tbl_users where username=’$user_check’ ");

$row=mysqli_fetch_array($ses_sql,MYSQLI_ASSOC);

$login_session =$row[‘username’];
$login_level =$row[‘level’];
$login_id =$row[‘id’];
$login_client_id =$row[‘client_id’];

if(!isset($login_session))
{
header(‘Location: …/login/index.php’);
}
else
mysqli_query($db,“UPDATE fms_tbl_users SET LastTimeSeen = NOW() WHERE id = $login_id”);
?>[/php]

Strider64 - I tried a few of your answers but kept hitting a wall. I am fairly new to php and learning as I go, sessions is a new one so it maybe I’m not implementing your answer properly.

astonecipher - my mysqli_connect.php code is;-
[php]<?php
define(‘DB_SERVER’, ‘XXX’);
define(‘DB_USERNAME’, ‘XXX’);
define(‘DB_PASSWORD’, ‘XXX’);
define(‘DB_DATABASE’, ‘XXX’);
$db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
?>[/php]

Hi guys, just a quick update and hopefully some help! :wink:

I’ve had to alter my functions and login process entirely as it was failing in several departments. I’ve looked on the internet and found a decent tutorial to create a secure login script.

I’ve implemented it and initial tests are coming back ok with no errors. My only issue is I still need a few lines of code to trigger other events within my system that I need to keep.

My new code basically has several bit and one is a functions.php file, in here it checks user details. I can echo the username correctly once logged in but I need further details from the database to be echoed such as ‘client_id’.

My new code is:-
[php]<?php

include_once ‘psl-config.php’;

function sec_session_start() {
$session_name = ‘sec_session_id’; // Set a custom session name
$secure = SECURE;

// This stop JavaScript being able to access the session id.
$httponly = true;

// Forces sessions to only use cookies.
if (ini_set('session.use_only_cookies', 1) === FALSE) {
    header("Location: ../error.php?err=Could not initiate a safe session (ini_set)");
    exit();
}

// Gets current cookies params.
$cookieParams = session_get_cookie_params();
session_set_cookie_params($cookieParams["lifetime"], $cookieParams["path"], $cookieParams["domain"], $secure, $httponly);

// Sets the session name to the one set above.
session_name($session_name);

session_start();            // Start the PHP session 
session_regenerate_id();    // regenerated the session, delete the old one. 

}

function login($email, $password, $mysqli) {
// Using prepared statements means that SQL injection is not possible.
if ($stmt = $mysqli->prepare(“SELECT id, username, password, salt
FROM members
WHERE email = ? LIMIT 1”)) {
$stmt->bind_param(‘s’, $email); // Bind “$email” to parameter.
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();

    // get variables from result.
    $stmt->bind_result($user_id, $username, $db_password, $salt);
    $stmt->fetch();

    // hash the password with the unique salt.
    $password = hash('sha512', $password . $salt);
    if ($stmt->num_rows == 1) {
        // If the user exists we check if the account is locked
        // from too many login attempts 
        if (checkbrute($user_id, $mysqli) == true) {
            // Account is locked 
            // Send an email to user saying their account is locked 
            return false;
        } else {
            // Check if the password in the database matches 
            // the password the user submitted.
            if ($db_password == $password) {
                // Password is correct!
                // Get the user-agent string of the user.
                $user_browser = $_SERVER['HTTP_USER_AGENT'];

                // XSS protection as we might print this value
                $user_id = preg_replace("/[^0-9]+/", "", $user_id);
                $_SESSION['user_id'] = $user_id;

                // XSS protection as we might print this value
                $username = preg_replace("/[^a-zA-Z0-9_\-]+/", "", $username);

                $_SESSION['username'] = $username;
                $_SESSION['login_string'] = hash('sha512', $password . $user_browser);

                // Login successful. 
                return true;
            } else {
                // Password is not correct 
                // We record this attempt in the database 
                $now = time();
                if (!$mysqli->query("INSERT INTO login_attempts(user_id, time) 
                                VALUES ('$user_id', '$now')")) {
                    header("Location: ../error.php?err=Database error: login_attempts");
                    exit();
                }

                return false;
            }
        }
    } else {
        // No user exists. 
        return false;
    }
} else {
    // Could not create a prepared statement
    header("Location: ../error.php?err=Database error: cannot prepare statement");
    exit();
}

}

function login_check($mysqli) {
// Check if all session variables are set
if (isset($_SESSION[‘user_id’], $_SESSION[‘username’], $_SESSION[‘login_string’])) {
$user_id = $_SESSION[‘user_id’];
$login_string = $_SESSION[‘login_string’];
$username = $_SESSION[‘username’];

    // Get the user-agent string of the user.
    $user_browser = $_SERVER['HTTP_USER_AGENT'];

    if ($stmt = $mysqli->prepare("SELECT password 
			      FROM members 
			      WHERE id = ? LIMIT 1")) {
        // Bind "$user_id" to parameter. 
        $stmt->bind_param('i', $user_id);
        $stmt->execute();   // Execute the prepared query.
        $stmt->store_result();

        if ($stmt->num_rows == 1) {
            // If the user exists get variables from result.
            $stmt->bind_result($password);
            $stmt->fetch();
            $login_check = hash('sha512', $password . $user_browser);

            if ($login_check == $login_string) {
                // Logged In!!!! 
                return true;
            } else {
                // Not logged in 
                return false;
            }
        } else {
            // Not logged in 
            return false;
        }
    } else {
        // Could not prepare statement
        header("Location: ../error.php?err=Database error: cannot prepare statement");
        exit();
    }
} else {
    // Not logged in 
    return false;
}

}

[/php]

Could you guys help with this final problem please? I need to be able to pull client_id from the database as well as the username

Guys, all sorted!!

I added the additional values to pull through when logging in, thanks again for all your help. No doubt I will have more PHP issues.

My final code for all that need it or are interested;-
[php]function login($email, $password, $mysqli) {
// Using prepared statements means that SQL injection is not possible.
if ($stmt = $mysqli->prepare(“SELECT id, username, password, client_id, salt
FROM members
WHERE email = ? LIMIT 1”)) {
$stmt->bind_param(‘s’, $email); // Bind “$email” to parameter.
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();

    // get variables from result.
    $stmt->bind_result($user_id, $username, $db_password, $client_id, $salt);
    $stmt->fetch();

    // hash the password with the unique salt.
    $password = hash('sha512', $password . $salt);
    if ($stmt->num_rows == 1) {
        // If the user exists we check if the account is locked
        // from too many login attempts 
        if (checkbrute($user_id, $mysqli) == true) {
            // Account is locked 
            // Send an email to user saying their account is locked 
            return false;
        } else {
            // Check if the password in the database matches 
            // the password the user submitted.
            if ($db_password == $password) {
                // Password is correct!
                // Get the user-agent string of the user.
                $user_browser = $_SERVER['HTTP_USER_AGENT'];

                // XSS protection as we might print this value
                $user_id = preg_replace("/[^0-9]+/", "", $user_id);
                $_SESSION['user_id'] = $user_id;

                // XSS protection as we might print this value
                $username = preg_replace("/[^a-zA-Z0-9_\-]+/", "", $username);

                $_SESSION['username'] = $username;
	    $_SESSION['client_id'] = $client_id;
                $_SESSION['login_string'] = hash('sha512', $password . $user_browser);

                // Login successful. 
                return true;
            } else {
                // Password is not correct 
                // We record this attempt in the database 
                $now = time();
                if (!$mysqli->query("INSERT INTO login_attempts(user_id, time) 
                                VALUES ('$user_id', '$now')")) {
                    header("Location: ../error.php?err=Database error: login_attempts");
                    exit();
                }

                return false;
            }
        }
    } else {
        // No user exists. 
        return false;
    }
} else {
    // Could not create a prepared statement
    header("Location: ../error.php?err=Database error: cannot prepare statement");
    exit();
}

}[/php]

and the link to the tutorial script;- http://www.wikihow.com/Create-a-Secure-Login-Script-in-PHP-and-MySQL

Sponsor our Newsletter | Privacy Policy | Terms of Service