8

I am having a bit of trouble. i am working on a small cms. When i login everything is fine. but if i sit there the session seems to require me to login again after 3 minutes maybe. so I tried to implement a remember me feature. and have no luck with it either. it also still require me to login.

in my functions I have the following code snip.

function logged_in(){

    if(isset($_SESSION['email']) || isset($_COOKIE['email'])){
        return true;
    } else {
        return false;
    }
}

Then i created another function that if the page requires login and your not logged in. it will redirect.

function require_loggin(){

    if (logged_in()) {} else {

        redirect(ROOT_URI);
    }
}

now on all the pages that require loggin i have this in the header of the page.

<?php require_loggin(); ?>

and this is my post data for the login page.

$email = clean($_POST['email']);
$password = clean($_POST['password']);
$remember   = isset($_POST['remember']);

and finally my login.

function login_user($email, $password, $remember){

        $active = 1;

        $connection = dbconnect();
        $stmt = $connection->prepare('SELECT user_pwd, user_email, uid, username FROM users WHERE user_email = ? AND active= ?');
        $stmt->bind_param('ss', $email, $active);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows == 1) {
            $row = $result->fetch_array();
            $db_password = $row['user_pwd'];

            if (password_verify($password, $db_password)) {

                if($remember == "on") {
        setcookie('email', $email, time() + 86400);
        }

                $_SESSION['uid'] = $row['uid'];
                $_SESSION['email'] = $row['user_email'];           
                $_SESSION['username'] = $row['username'];

                return true;
            } else {
                return false;
            }
            return true;
        } else {
            return false;
   }
}

everything works with no error. login and logout are fine..

The issue is that once they login the default session dies in about a 4 minutes if they are not clicking links. and the remember me function wont work.. I read some where that a default session should last about 30 minutes. but the session requires login after 4 minutes of not moving through the site.

Someone mentioned to me about Garbage Collection but I have to admit I am totally lost on it.

I am still fairly new to php and I want to learn the correct way not the incorrect way. my project works great i just cannot keep a user logged in or get the remember me to function.

Brad Larson
  • 170,088
  • 45
  • 397
  • 571
Case
  • 281
  • 4
  • 26
  • 2
    your cookie name is "mycookie" when you set it but you check for key "email" – Benjamin Oct 24 '16 at 19:01
  • I didn't understand the question. You said that when the user closes the browser after logging in with the option "remember me" and reopens the browser, he remains logged in, right? Isn't it the desired effect? – Vinicius Dias Oct 24 '16 at 19:13
  • @Vinicius Dias if a user is logged in i have a function that redirects them from the login page and register page if they login with remember checked, then they close there browser and reopen it redirects them from the login page as though there logged in but they are really not. – Case Oct 24 '16 at 19:24
  • The cookie stays set for 1 day, even if the user restarts the browser. Why are you using a cookie instead of just the session variable? – Barmar Oct 24 '16 at 19:26
  • It seems like you shouldn't be checking the cookie in `logged_in()`, just check the session variable. – Barmar Oct 24 '16 at 19:29
  • 1
    I'm voting to close this question as off-topic because the question has changed significantly multiple times which has led to confusing and misleading answers. – Robbie Nov 03 '16 at 23:15
  • lol you didnt get the bounty so now you want to close it lol smh – Case Nov 04 '16 at 19:06
  • 2
    Completely changing your question such that it invalidates existing answers is disrespectful to those who have taken the time to help you, and is frowned upon here. Your last edit made the question nonsensical, so I've rolled it back to the way it was when you provided the bounty. If you have a new question to ask, do so in a brand new question. – Brad Larson Nov 04 '16 at 21:53
  • Sometimes when we are discovering something new we don't really know what to ask.. and as information comes in the actual question emerges. Not to mention people attempting to answer the question my request additional information which naturally changes the scope. – Layton Everson Nov 07 '16 at 04:19

7 Answers7

6

I recommend creating an application config file.. call it config.php and include it at the top of your pages. As simple as your application appears I'm assuming your not using an auto loader. Include the following snippit in it:

<?php
    /**
     * File: config.php
     * This file should be included in every php script to configure the session. Like this:
     * require_once('config.php');
     */

    /*
     * This is 30 minutes. The length only depends on the requirements of 
     * your application. 
     */
    $sessionLength = 30 * 60; 
    ini_set(’session.gc_maxlifetime’, $sessionLength);
    ini_set(‘session.gc_maxlifetime’,30);

    session_set_cookie_params($sessionLength , "/", "yourdomain.com")
    session_name('PHPSESSION'); 
    session_start(); 
    //This will force the cookie to reset with a new timeout on every page load.
    setcookie( session_name(), session_id(), time() + $sessionLength );

?>
Layton Everson
  • 1,148
  • 9
  • 18
4

Update:

Edit number 9 of the question has changed the question quite dramatically and this answer (and most of the other answers) no longer apply.

This answer was in response to edit number 7 of the question (when the bounty was started).

Leaving this here so visitors know why there are so many answers and comments relating to "session length" when the question, as it currently stands, does not reference it. Will delete the answer when wrapped up.


Run the following php file in your browser:

<?php

echo 'Session Cookie Lifetime: '. ini_get('session.gc_maxlifetime') . ' (The number of seconds after which data will be seen as \'garbage\' and potentially cleaned up.)<br>';
echo 'Session Cookie Lifetime: '. ini_get('session.cookie_lifetime') . ' ( the lifetime of the cookie in seconds which is sent to the browser. The value 0 means &quot;until the browser is closed.&quot;)<br>';

phpinfo();

?>

If either of the two values at the top are "around 4 minutes" (240 seconds) then you need to adjust them in your PHP config.

Failing that, the phpinfo() output below should tell you all you need to look for: e.g.

  • if you have another script that deleted files from the session path (see "session Save Path" in ) then you'll also lose the session;
  • if you're not using cookies (I assume you are, otherwise you'll see a PHPSESS parameter on all the URLs) then
  • if PHP/Apache/ISS etc should "restart" then you'll lose all the sessions
  • (Don't be fooled by session.cache_expire=180; that 180 is minutes, not seconds, and unrelated to this.)
Robbie
  • 17,605
  • 4
  • 35
  • 72
  • excelent answer – Nick Oct 27 '16 at 05:09
  • actually Robbie none of the answers answered my question – Case Oct 28 '16 at 03:40
  • also the code has not changed dramatically only 4 lines were added to this part of the code – Case Oct 28 '16 at 03:41
  • Code might not have changed, but the "problem" (and thus your question) has. The core of the previous question (version 7) was "The issue is that once they login the default session dies in about a 4 minutes if they are not clicking links. and the remember me function wont work.. I read some where that a default session should last about 30 minutes. but the session requires login after 4 minutes of not moving through the site." You've now removed that and shifted focus to just the "remember me" not working. Anyhow - see the other answer. – Robbie Oct 28 '16 at 04:20
3

Based on the latest edit of your question (9), and the codebin as it stands right now (please stop editing the question and code - create a new question if it changes that much!)

Your call to login_user($email, $password) does not pass the $remember variable as expected in the declaration

function login_user($email, $password, $remember)

So it'll never set the cookie.

Tips:

  • when debugging, just type echo $remember . "<br>"; or echo "I'm Here<br>; or echo "I'm at " . __FILE__ . "/" . __LINE__ . "<br>"; or similar in your code at various points so you know where it's tracking. You'll see that it never gets to the "setcookie" line
  • turn on ALL error reporting for debug/development purposes. error_reporting(E_ALL); and ini_set('display_errors', 'on'); as this will reveal your problem
  • If you use a cookie, don't store something easily decodable (like a base64 string, as you are doing) but store reference to a "permanent session" you save on the server. Any hacker would instantly recognize a base64 string (see those equals sign(s) at the end? - base64 is the first thing that springs to mind). I could change one letter and log in as someone else using your code.
  • There are some more tips about creating a good session system (i.e. if you're using cookies for "remember me", then you may as well not use the session_start() sessions and do it all yourself) but that then leads to suggestions you should use a library if you're not 100% sure of your logic and security - and given the base64_decode issue that's true. Hopefully your verify_password is not self-written but something commmercial? Perfect for learning but have someone check over the code before launching if you want it to go live.

Good luck

(And please, don't change the question again! No one will want to help you.)

Robbie
  • 17,605
  • 4
  • 35
  • 72
2

First of all try adding this line before your 'session_start()' statement:

session_set_cookie_params(3600,"/");

If that did not work, You have 3 options:

1) Change the value of this line in your php.ini to 1800

session.gc_maxlifetime

2) Put this in your .htaccess file:

php_value session.cookie_lifetime 1800
php_value session.gc_maxlifetime 1800

1800 is in seconds, so it is half an hour.

3) If you dont have access to .htaccess, you can put this in your header:

ini_set('session.cookie_lifetime','1800');  

Debian has a cron job to automatically expire sessions for security measures. If you are using Debian check /etc/cron.d/php*

RESOURCES:

http://php.net/manual/en/session.configuration.php#ini.session.cookie-lifetime http://php.net/manual/en/function.session-set-cookie-params.php

Eilat
  • 73
  • 1
  • 1
  • 5
0

you have not mention how u r using logged_in function?
when you close a browser your session will destroy so userid, username, email value will be null.
After checking a cookie value is set or not based on cookie value you have to fetch corresponding values from database and set the values in session. you have to follow this kind of flow for acheaving persistance login system. I hope this answer help u in understanding this login system.

Anant Waykar
  • 662
  • 2
  • 8
  • 18
0

Check Robbie answer.

In case you can not adjust PHP configuration you can use HTTP Auth as well. It does not expires. However in this case, the password is transmitted every time visitor request a webpage.

Nick
  • 9,962
  • 4
  • 42
  • 80
-3

This is a wrong way to handle this. In order to implement cookie auto login, you should store all your required login data in the cookie. But you must encrypt them to prevent problems later.

Example Cookie:

toke = USER_ID:USER_NAME:HASHED_PASSWORD

The colon is the separator so you can use explode to get components of the login token. Then you can check these info with the database entries.

Good Luck!

hmak.me
  • 3,770
  • 1
  • 20
  • 33
  • Never store passwords on cookies. Not even hashed passwords. – David Rojo Oct 26 '16 at 22:22
  • @DavidRojo So how you're gonna implement "remember me" in your login process? – hmak.me Oct 28 '16 at 05:46
  • 1
    You can create a token without exposing any personal data as id, user name or password and then in your database in a table you have the relation of the token and the user id. http://stackoverflow.com/questions/244882/what-is-the-best-way-to-implement-remember-me-for-a-website/244907#244907 – David Rojo Oct 28 '16 at 09:01