Jump to content

Recommended Posts

Hello Everyone!

 

I have 2 problems with sessions that I'd like some assistance with.

1. The session often ends after clicking any link after logging in. (sometimes it remains alive, and in those cases it stays alive until browser is closed.)

2. The function that should start a session if a cookie is found (and correct) is not working, so if the browser is closed and re-opened the session won't start the session.

 

I'll include the code that I think is relevant. The odd part is that these problems occur in every browser, I have tried multiple tutorials (so different scripts) to creating a login form but somehow the same result appears every time.

 

function login($username, $password, $remember = false) 
{


    $sql = mysql_query("SELECT * FROM users WHERE password = '" . md5($password) . "' AND username = '" . $username . "' LIMIT 1");
    // If there are no matches then the username and password do not match
    if($sql === false) 
    {
        return false;
    }
    else
    {
        while($u = mysql_fetch_array($sql))
        { 
                
                // Check if user wants account to be saved in cookie
                if($remember == true)
                {
                    // Generate new auth key for each log in (so old auth key can not be used multiple times in case 
                    // of cookie hijacking)
                    $cookie_auth= rand_string(10) . $username;
                    $auth_key = session_encrypt($cookie_auth);
                    $auth_query = mysql_query("UPDATE users SET auth_key = '" . $auth_key . "' WHERE username = '" . $username . "'");

                    setcookie("auth_key", $auth_key, time() + 60 * 60 * 24 * 7, "/", "mycorrectwebsite.com", false, true);
                }
                // Assign variables to session
                session_regenerate_id(true);
                $session_id = $u[id];
                $session_username = $username;
                $session_level = $u[user_level];

                $_SESSION['user_id'] = $session_id;
                $_SESSION['user_level'] = $session_level;
                $_SESSION['user_name'] = $session_username;
                $_SESSION['user_lastactive'] = time();
			return true;
        }
    }
} 

function initiate()
{
	$logged_in = false;
	if(isset($_SESSION['user_name']))
	{
		$logged_in = true;
	}

        // Check that cookie is set
        if(isset($_COOKIE['auth_key']))
        {
            $auth_key = $_COOKIE['auth_key'];

            if($logged_in === false)
            {
                // Select user from database where auth key matches (auth keys are unique)
                $auth_key_query = mysql_query("SELECT username, password FROM users WHERE auth_key = '" . $auth_key . "' LIMIT 1");
                if($auth_key_query === false)
                {
                    // If auth key does not belong to a user delete the cookie
                    setcookie("auth_key", "", time() - 3600);
                }
                else
                {
                    while($u = mysql_fetch_array($auth_key_query))
                    {
                        // Go ahead and log in
                        login($u['username'], $u['password'], true);
                    }
                }
            }
            else
            {
                setcookie("auth_key", "", time() - 3600);
            }
        }

}

 

And then in the header I start every page with:

 

<?php 
session_start();
include("connect.php");
include("functions.php");
include("actions.php");

initiate();
?>

Link to comment
https://forums.phpfreaks.com/topic/258376-session-problem/
Share on other sites

I can see how that went wrong, your solution didn't have the desired effect so I tweaked it a little more.

 


function initiate()
{
	if(isset($_SESSION['user_name']))
	{
		// Do nothing since session is running!
	}else{

        // Check that cookie is set
        if(isset($_COOKIE['auth_key']))
        {
            $auth_key = $_COOKIE['auth_key'];

                // Select user from database where auth key matches (auth keys are unique)
                $auth_key_query = mysql_query("SELECT username, password FROM users WHERE auth_key = '" . $auth_key . "' LIMIT 1");
                if($auth_key_query === false)
                {
                    // If auth key does not belong to a user delete the cookie
                    setcookie("auth_key", "", time() - 3600);
                }
                else
                {
                    while($u = mysql_fetch_array($auth_key_query))
                    {
                        // Go ahead and log in
                        login($u['username'], $u['password'], true);
                    }
                }
            
        }
}
}

 

Frankly, Nothing really changed. After closing both chrome and firefox and reopening it, the session wasn't turned alive when visiting the site. I checked the cookies and both were there, equal to the value in the database field, still it didn't activate the login function.

Link to comment
https://forums.phpfreaks.com/topic/258376-session-problem/#findComment-1324421
Share on other sites

I may be misreading things here, but from what I can see you're storing the an MD5 hash of the password in the database.

 

Your login($user,$password) function converts the raw password to the hash automatically.

 

When you have a cookie saved, you retrive the users row by the auth_key and now you have.

$u['username'] - The users username

$u['password'] - The MD5 hash of the password.

 

Then you do the login($u['username'],$u['password']) function.

The login should fail because you're using the hashed password to login with, not the raw password.

Link to comment
https://forums.phpfreaks.com/topic/258376-session-problem/#findComment-1324455
Share on other sites

I would do it like this:

function login($username, $password, $remember = false) 
{


    $sql = mysql_query("SELECT * FROM users WHERE password = '" . md5($password) . "' AND username = '" . $username . "' LIMIT 1");
    // If there are no matches then the username and password do not match

    // If the number of rows fetched was greater than 0, the username and password matched.
    if(mysql_num_rows($sql) > 0)
    {
        while($u = mysql_fetch_array($sql))
        { 
                
                // Check if user wants account to be saved in cookie
                if($remember == true)
                {
                    // Generate new auth key for each log in (so old auth key can not be used multiple times in case 
                    // of cookie hijacking)
                    $cookie_auth= rand_string(10) . $username;
                    $auth_key = session_encrypt($cookie_auth);
                    $auth_query = mysql_query("UPDATE users SET auth_key = '" . $auth_key . "' WHERE username = '" . $username . "'");

                    setcookie("auth_key", $auth_key, time() + 60 * 60 * 24 * 7, "/", "mycorrectwebsite.com", false, true);
                }
                // Assign variables to session
                session_regenerate_id(true);
                $session_id = $u[id];
                $session_username = $username;
                $session_level = $u[user_level];

                $_SESSION['user_id'] = $session_id;
                $_SESSION['user_level'] = $session_level;
                $_SESSION['user_name'] = $session_username;
                $_SESSION['user_lastactive'] = time();
			return true;
        }
    }
} 

 

Also, I don't know a lot about how cookies work browser side, but you should probably sanitize the inputs in login(). incase someone can edit the cookie and do an SQL injection.

Link to comment
https://forums.phpfreaks.com/topic/258376-session-problem/#findComment-1324694
Share on other sites

Thanks for the input ttocskcaj, I'm now using

$num = mysql_num_rows($sql);
    // If there are no matches then the username and password do not match
    if($num != 1) 
    {
        return false;
    }else{
        $u = mysql_fetch_assoc($sql);

 

Which eventually will have the same result.

I've put an escape string on the part where to cookie is being compared to the database fields now, to make sure the code won't be messed up there. If a match is found the username and password from the same row is used in the login() function. As far as my knowledge goes on PHP the user won't be able to change values there.

Link to comment
https://forums.phpfreaks.com/topic/258376-session-problem/#findComment-1324787
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.