473,715 Members | 2,186 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

stay logged in & remember me - PHP sessions and cookies

9 New Member
Looking for guidance on how to accomplish the following.

Default login:
User is logged in with a session lifetime of 25 minutes, or until the browser closes:
Expand|Select|Wrap|Line Numbers
  1. // path for cookies - valid for all paths in domain
  2. $cookie_path = "/";
  4. // timeout value for the cookie
  5. $cookie_timeout = 60 * 60 * 25; 
  7. // timeout value for the garbage collector
  8. $garbage_timeout = $cookie_timeout + (60 * 10); //cookie + 10 minutes 
  10. session_name();  // dynamically set - beyond question scope  
  11. session_id(); // dynamically set - beyond question scope
  13. session_set_cookie_params($cookie_timeout, $cookie_path);
  15. // set the garbage collector to clean the session files
  16. ini_set('session.gc_maxlifetime', $garbage_timeout);
  18. // set new session directory to ensurer unique garbage collection
  19. $sessdir = ini_get('session.save_path').DIRECTORY_SEPARATOR."visitor";
  20.         if (!is_dir($sessdir)) { mkdir($sessdir, 0777); }
  21.         ini_set('session.save_path', $sessdir);
  22. session_start();
Now, there are two functions that I want to incorperate with the login feature:
1 - Stay Logged In
  • I want the users session to remain valid for as long as the browser is open.
  • I believe this could be accomplished by setting the session.cookie_ lifetime = 0, either in the session_set_coo kie_params() or later in setcookie() by setting expire = 0.
  • I also understand it to be true that if I issue a cookie with an expire setting different that my default setting, I would want to save this cookie into a different session director (perhaps "stay_logge d" instead of "visitor" as above?). This is necessary to ensure that the server side session file is not impacted by a conflicting garbage collection process.
2 - Remember Me
  • I want the system to remember the users login name, so that when they return to the site their name can auto populate into the name field of the login screen.

...this is where I'm struggleing conceptually. If the user selects both remember me, and stay logged in, they are expecting this session to remain valid until the browser closes as well as have their name populate when they return later. Since the stay logged in feature sets the expire time to = 0 on the cookie, my cookie is invalid after that point. Thus, I can't recall the users name on a returning visit. If I set the expire time to = 30 days, so i have access to the user name, then I am unable to keep the user logged in until the browser closes because I most likely will be doing login status checks to compare expire time to last refresh time...

I hope I've kinda got'n the idea across that I'm struggling with. Stay logged requires an expire time = 0, while remember me requires an expire time = 30.

What if my user wants both options??
Feb 7 '10 #1
11 22961
9 New Member
** new thoughts **

should I only adjust the $cookie_timeout value for session_set_coo kie_params() from 25min to 30 days if the user sets the 'remember me' preference. And use the setcookie() expire time only for a $login_status variable in regards to the 'stay logged in' preference? Therefore, the $login_status is the only variable not saved in the cookie at the closing of the browser, but the other cookie variables will persist (between 25minutes and 30 days, dependant upon the 'remember me' selection)?

Feb 7 '10 #2
1,044 Recognized Expert Top Contributor
You may not be getting the way that this works.

"Remember Me" only has an affect on the login page. When a user is attempting to log in, their username is loaded from a "Remember Me" cookie. It is only used before a user logs in, and is only set as a user is logging in.

As for "Stay Logged In," this is not meant to make a session live after the browser is closed. It is meant to keep the user authenticated each time that they visit the website and they are not logged in. In this case, when you check if the user is logged in (which should be done on every page that is different based on the authentication status, which is typically all pages), if they are not logged in, you check their cookie for an authentication "key." This key must match the corresponding key in your database. If it does, then you should count it as the same thing as providing a correct username and password combination.

The key should be generated/updated every time that the user logs in. This decreases the likelihood of a malicious user finding this key and using it, at least more than once. Auto-login is never the most secure method of logging in, but you should do what you can to add to its security.
Feb 8 '10 #3
9 New Member
Thank you for your reply Kovik.

I have some questions related to convention of login systems. I've reviewed instruction on the basic process, but I want to establish a solid understanding.

Since you referred to a database, I'd also like to have mention of sessions here when applicable.

___Remember Me___
I believe what you explained was comparable to the original post:
"...remembe r the users login name, so that when they return to the site their name can auto populate into the name field of the login screen."
When a user is attempting to log in, their username is loaded from a "Remember Me" cookie
You stated, '...a "Remember Me" cookie.' Does this imply that you use one cookie just for the Remember Me function, and perhaps generate and issue a seperate cookie for current activity? I say this, because the only way I know how to end a session on browser close is by setting the cookie lifetime to 0, therefore having nothing to reference on a return visit.

__Authenticatio n Key____
If I understand you correctly, the auth_key set in the cookie indicates that the user has already been verified (is logged in). When a user goes to a new page, I would check for an auth_key and compare it to stored database (or session?) info. If it is missing/expired/invalid, then redirect to a login page where a new auth_key could be established?

If this is the case, why not just updated a var in the session (or database) indicating the user is logged in and access this info by means of the session id from the recieved cookie?

To clarify, what I was intending by default was to have a session die after 25 minutes of inactivity. If the user attempts to access a privelaged page after 25 minutes, they will be required to login again. However, if the user selects "Stay Logged In" at login, long periods of inactivity are permitted but the session still dies if the browser closes.

Is this handling uncommon or unacceptable?

I am not trying to have any type of auto-login function.

Thank you for your time and attention, it's all too often I over/under think tasks that are trivial to those more experienced.
Feb 18 '10 #4
1,044 Recognized Expert Top Contributor
Yes, the "Remember Me" cookie is one cookie. It's expiration date should be far into the future (about a year or so), and only include the value of the user's login name.

Your view on session handling seems a bit inaccurate. Basically, accessing a session is just like having an auto-login script. The session ID (similar to the authentication key) is stored on the clients PC in a cookie. PHP then uses this ID to fetch the session data for that user. As for the expiration of sessions, forcing expiration is easily done if you store your sessions in the database by only accepting sessions that are still considered "active" by your standards, and increasing their time limit on every page request. Doing this using PHP's default filesystem-based session handling isn't nearly as simplistic.

Now, you want to have a user's session stay alive if they select "Stay Logged In," but if they do not, you want it to expire after 25 minutes? You're going about this all wrong, then. No cookies are needed, and no authentication key is needed.

Firstly, I'd highly suggest that you store your sessions in the database for making this process easier. Now, what you want to do is have your basic sessions table (ID, data, and expiration), and add a "persist" flag. This flag will be true when a user wants their session to stay alive, and false when they want to enable its expiration.

Then whenever you attempt to load a session, you do a simple check. If "persist" = true, then load the session. Else, check the expiration. If the session is expired, destroy it. Otherwise, load the session.
Feb 18 '10 #5
9 New Member
Thank you kovik.

Some things have clicked for me here. I hadn't considered NOT using the php session functions. Originally, I had planned to only use the db to hold long term info (user preferences, personal information, encrypted password, ect...) and the PHP Session for short term data (login and verifcation status, submitted form filed values to allow for field repopulation incase a user clicks BACK/FORWARD on the browser, page access times for session life-cycle, ect...).

Using only a cookie and db for access control seems simplified and easily customizable. However, (besides from the dramatic increase in db reads/writes/deletes this will create) you're missing a key response that I'm looking for. I only want the Stay Logged In to persist for the currently opened browser. When the browser closes, I want the session to be terminated. With your suggestion, I would be able to open a new browser and access the site without verification.

Consider a situation of a working environment. An employee logs in, keeping the webpage open all day but never actually using it. Bringing the site up is just procedure, although it might not get used for that day. At the end of the day, the employee just closes the browser (instead of clicking a log off button like they should). Then the individual fails to shutdown/lock their workspace and leaves. A malicious person could simply open a new browser on the computer and access the web site without verification. No good.

Perhaps I could use your system with two cookies:
  1. A 'Remember Me' cookie, containing a username, with an expire time of 1 year, cookie path of ' /login ', and have the PHP login script in a 'login' directory to ensure proper sending and receiving of this particular cookie between the script and browser.
  1. A 'Stay Logged In' cookie, containing an auth key, with an expire time of 0 (to destory the cookie when the browser closes) and a cookie path of ' /user'. All pages requiring authentication will be kept in the 'user' directory.
This way:
Log in without 'Stay Logged In' uses page access times stored in the database to determine if the ..."session" (for lack of a different word) is still valid (within 25 minutes from last page view). If greater than 25 minutes, redirect to /login. This default process occurs if there is not a stored auth_key in the db.

Log in with 'Stay Logged In' updates the database with an auth_key and issues the SLI cookie. Subsequent page visits require the cookie and db auth_keys to match. If no auth key is available / no cookie recieved / invalid auth key, redirect to /login and clear the auth_key in the db.

Since 'Remember Me' cookie is attributed to the /login directory, it will always be avialable (until 1 year of inactivity has passed). Since all pages requiring authentication are in the /user directory, they will obtain the 'Stay Logged In' cookie if it is set.
Feb 19 '10 #6
1,044 Recognized Expert Top Contributor
Again, I still think that you are unclear of how sessions work.

Sessions are a set of server-side data with a unique ID. This ID is saved on the clients computer in a session cookie. A regular cookie persists until its expiration date, at which point the browser deletes it. A session cookie persists until the browser says so. So, for example, I believe that Firefox will destroy session cookies once the firefox.exe process stops running. It is possible to close Firefox and reopen it within a few minutes before the process ends, allowing accidental browser closings to not interrupt your session.

There is no way for you to detect a browser closing. But the difference between a regular cookie and a session cookie is that, by design, session cookies are meant to be destroyed upon closing of the browser.

However, if you are really concerned with checking if the browser is still open (since you cannot check if it is closed), you could make periodic client-side AJAX requests that inform the server that the user still has one of your webpages up in one of their tabs.
Feb 19 '10 #7
9 New Member
What is incorrect about my last post specifically?
Feb 19 '10 #8
1,044 Recognized Expert Top Contributor
This is the *only* way that sessions are used. You don't have any other option. Sessions store temporary data.

Although the session will still technically exist, once the user's session cookie is destroyed, they no longer have access to it. How would they open a browser and magically obtain a deleted cookie?

This is up to the browser. Why have a "Stay Logged In" function if you want it to log them out without them logging themselves out?
Feb 19 '10 #9
9 New Member
Are you reading my post or scanning them?
Feb 19 '10 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

by: dr. zoidberg | last post by:
Hello, I have created simple login sistem. I'm using sessions and they expire after I close my browser. How can I stay loged after I have closed my browser window? I know I should use cookies, but I'm interested in some tips and tricks. TNX
by: Joshua Beall | last post by:
Hi All, What is the best way to use a cookie to remember a logged in user? Would you store the username and password in two separate cookies? Should the password be plain text? Hashed? Not there at all? Any feedback would be helpful. Thanks! -Josh
by: TG | last post by:
This is more of a pain than I thought it would be. I need a simple code segment to determine whether a browser accepts cookies or not. When I pass variables between pages when cookies are turned off, the global variables are empty between pages, fine, that tells me cookies store the global variables - right? I store the values in $_session and when cookies are turned on values are passed between web pages - I can see these values in fields...
by: baylor | last post by:
i'm using forms authentication. i would like for a user to be logged in until they close the browser. The FormsAuthentication.RedirectFromLoginPage method takes the parameter createPersistentCookie. For some reason i thought this meant it either wrote a cookie that lasted for 50 years or a cookie that existed until the browser closed. Apparently i guessed wrong If i set createPersistentCookie to false, i am logged out after 20 minutes. i...
by: magic_hat60622 | last post by:
Hi all. I've got an app that dumps a user id into a session after successful login. the login page is http://www.mydomain.com/login.php. If the user visits pages on my site without the www (i.e., http://mydomain.com/foo.php), the session works fine and login state is maintained. If he visits http://www.mydomain.com/foo.php, the app drops the logged-in state.
by: Ben Holness | last post by:
Hi all, I have a php/mysql website where people can upload their own graphics for the buttons and background of pages on the website. This used to run on one server, but I have now been asked to set it up on multiple servers. The problem is that when someone uploads a file, how do I distribute it to all of the servers? Should I use php to send it to all of the servers once
by: cassbiz | last post by:
I am almost finished with a script and currently all users are using a preset user and pass. Currently I am using sessions but I want guests to be able to come to the site without using a user and pass for the general public pages. What is the best recommendation? The software is for campground and B and B reservations.
by: Simon Dean | last post by:
Hi, I believe I have a website (I didn't do the original coding) which uses JavaScript/ASP to generate cookies. It's a shopping cart application called UCart I believe. The technologies involved are: ASP
by: rsbgm | last post by:
Dear All, Ok. Here I am again for some answers. I've gotten to understand more of things from here than other places. I hope I don't get spoiled. LOLZ... Associative Array is an array that uses names or strings as indeces of the data stored (instead of the usual 0,1,2.. numbers). Am I right? So, in $_SESSION, I can store $_SESSION, $_SESSION, or whatever I want as many as I can (discretely) in one user session, right? And, I can call...
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.