Jump to content

What is the ideal / proper way to deal with SESSIONs ?


moose-en-a-gant

Recommended Posts

I built a website that has multiple users accessing it at once, there is a problem with the sessions. People are getting directed to a logged out page. I know why this is because I don't thoroughly understand how to use sessions.

I have picked up about storing in places other than /tmp , I'm concerned about storage and not carrying it from one page to the next

 

So when a person logs in, then they hit back on their browser or exit it (for a phone) and go back to it, they should still be logged in. That doesn't happen, they are usually logged out.

 

Also there is a weird anomaly. When I use the website on my device (phone) I don't have a problem of session value getting lost and the website exists on a server / computer that is not this phone, so why does my friend have problems with sessions but not me?

 

This is my general session code, it is garbage

<?php
ob_start();
session_start();

if( !isset($_SESSION['last_access']) || (time() - $_SESSION['last_access']) > 60 )
  $_SESSION['last_access'] = time();

session_save_path('/home/admin2/public_html/sesh');
ini_set('session.gc_probability', 1);

$userrname = $_SESSION["user"];
$_SESSOIN["user"]=$userrname;

if (empty($userrname)){
header("Location: ");
}
?>

I'd appreciate any help.

 

Thank you.

Link to comment
Share on other sites

This:

session_save_path('/home/admin2/public_html/sesh');
ini_set('session.gc_probability', 1);

should also come before session_start(), and especially before you start using $_SESSION or it won't have the correct session path to look the session data up

Link to comment
Share on other sites

I read on the manual, there was a "Warning" about using /tmp so I figured a person who was so inclined could look up /tmp folder path. I don't know if that is true eg. if it is in the same folder as public_html

 

I am having a weird problem.

 

My friend was testing my website for me and he can't keep his session, so he is automatically redirected to a "you've been logged out" page.

 

When I hand him my phone, he loggs in, he stays in... I have a windows phone and he has like an S5 or something.

 

It's odd because both of our phones are independent of the server that has the files on it... so why does my phone work and not his?

 

I haven't made the changes yet of the folder path.

 

And is that dumb to keep setting the session value on each page so that they are "carried over" to the next page?

Edited by moose-en-a-gant
Link to comment
Share on other sites

I don't think it makes sense to write a bunch of random garbage code (your words) and then try to somehow debug it. This strategy may work for simple tasks, but it hardly works for actual web applications.

 

So before you do anything, it's important that you fully understand how sessions work. Read the manual, search the web, and if there's still something you don't understand, ask.

Link to comment
Share on other sites

On php.net - http://php.net/manual/en/function.session-save-path.php

 

Session data path. If specified, the path to which data is saved will be changed. session_save_path() needs to be called before session_start() for that purpose.

 

 

I realise CroNIX has already conveyed that to you...just thought I'd reinforce that and Jacque1's advice regards understanding sessions..

 

Let us know if the fixes suggested here have worked when you have applied them.

 

Good luck.

Link to comment
Share on other sites

yeah I'm trying to use the mobile version of the website and when I go from one browser page to another, the session value is lost...

 

I use a windows phone, I'm not sure how I can get around this problem

 

To re-iterate, if I am in the website, and I open up a new browser page, copy something in the new browser page, go back to to the first browser page, the session value is unset...

 

What should I do? Or is this... well I can log into other websites and refresh / navigate between web pages and not lose the session value eg. stay logged in so it must be my code.

Link to comment
Share on other sites

Have you made the changes suggested? Do you have a better understanding of sessions now? Perhaps you could post what code you now have for us.

 

edit: does session_start() exist on each of the pages you are visiting?

Edited by wezhind
Link to comment
Share on other sites

Create a minimal example which uses plain PHP sessions with no fancy stuff whatsoever (no custom save path, no playing with the garbage collector). For example, create two scripts like this:

<?php

session_start();

?>

<h2>The cookies:</h2>
<?php var_dump($_COOKIE); ?>

<h2>The current session content:</h2>
<?php var_dump($_SESSION); ?>

<?php

$_SESSION['visited_page_1'] = true;    // in the other script, it's "visited_page_2", of course

?>

Now you can systematically debug the problem: Is the cookie set and transferred correctly? Does PHP open the right session file?

Link to comment
Share on other sites

Create a minimal example which uses plain PHP sessions with no fancy stuff whatsoever (no custom save path, no playing with the garbage collector). For example, create two scripts like this:

<?php

session_start();

?>

<h2>The cookies:</h2>
<?php var_dump($_COOKIE); ?>

<h2>The current session content:</h2>
<?php var_dump($_SESSION); ?>

<?php

$_SESSION['visited_page_1'] = true;    // in the other script, it's "visited_page_2", of course

?>

Now you can systematically debug the problem: Is the cookie set and transferred correctly? Does PHP open the right session file?

 

Hi thanks for all of your help (including person above ^^), I haven't implemented the changes yet.

 

I just noticed this problem on the mobile version. I haven't actually used cookies, only sessions, do you need them both?

 

I'm going to implement the changes today. I just have to get a different project finished so that I can advertise that and while I wait I will further hone this website.

 

Thanks for your help.

Link to comment
Share on other sites

I'm working on this now, I'm wondering if cookies are not enabled on the client' side, if sessions are interchangeable, my current train of thought is to set the session value using the username then pass this to the cookie and both can be used...

 

I think the key is session is server, cookie is client... so in my case of the phone, that's probably was is going on. I'm going to implement the changes...

 

3:56 AM, I have 8 pages to modify

 

I'm wondering what is an appropriate session / cookie lifetime, a day? or an hour? not sure...

 

I have to read up / picked this code up too, I don't know when it is triggered

ini_set('session.gc_probability', 1);

4:54 AM

 

Okay so, so far... this is what I'm doing... this seems redundant eg. dumb

 

These are in order but not necessarily sequentially just in terms of hierarchy

 

This is on index, / mobile-index

session_save_path('/home/admin2/public_html/sesh');
ini_set('session.gc_probability', 1);
session_start();

$_SESSION['user']=$userrname;
                   $cookie_name = "user";

Then I get redirected to a new page, userpanel or userpanel-mobile

 

This is where it gets redundant ** actually I may have fixed the redundant part

 

These three again are together and precede the rest

session_save_path('/home/admin2/public_html/sesh');
ini_set('session.gc_probability', 1);
session_start();

if( !isset($_SESSION['last_access']) || (time() - $_SESSION['last_access']) > 60 )
  $_SESSION['last_access'] = time();

if(empty($_COOKIE)){
$userrname = $_SESSION['user'];
}else {
$userrname = $_COOKIE[$cookie_name];
}

the if...last_access thing is another piece of code I picked up randomly, not sure if I need it.

 

so far this works on laptop, I have to test it on mobile which I have to redesign the interface.

Edited by moose-en-a-gant
Link to comment
Share on other sites

Please don't just write down random code. This ini_set('session.gc_probability', 1) you keep carrying around makes absolutely no sense whatsoever. First of all, why would you want to change the probability of the session garbage collector at runtime? What are you trying to achieve? Secondly, the probability is defined with two numbers, the numerator and the divisor. You can have a probability of, for example, “1 in 1000”, but “1 in undefined” is obviously nonsense.

 

Random code only causes bugs, and additional bugs are pretty much the last thing we want right now.

 

Do this systematically. What were your results with the example code I posted? If you clear all your cookies, visit the first script and then visit the second script, what's the output?

Link to comment
Share on other sites

I've got a little bit of time, so I'll try and explain, BUT you really should do a tutorial on sessions. A simple one to begin with just to get the basics.

 

I'm going to ignore the 'standard' cookie approach for now and just try and explain session cookies. I personally only use 'standard' cookies for things like when a user checks a 'Remember me' checkbox when they login, so next time they return to the site - the site looks for a 'standard' cookie previously saved (when they logged in with the 'Remember me' checkbox checked) and if it finds it, it bypasses the login procedure and they are automatically logged in). For the purposes of determining if somebody is still logged in from page to page, I use the appropriately named 'session' cookies. This seems like what you are trying to do, so I will explain this side.

 

Firstly, EVERY page that a user will visit between logging in and logging out should have session_start() at the top of the page. There should be no output to the screen before this (i.e. no echo statements, no html). So your first line of every page should look similar to this...

<?php session_start(); //this resumes an existing session if it exists or starts a new one if it doesn't

...UNLESS you want to configure something about the session i.e. where on the server the 'session' cookie should be stored. This is usually unnecessary, but if configuration is required then those settings must be made before the session starts and would therefor look like this:

 

<?php session_save_path('/home/admin2/public_html/sesh');
session_start();

Note: the path you used would mean that the 'session' cookie would be stored in the public part of your site, which I wouldn't advise. I believe the default would be safer.

 

So that's the first part. For now, I would just stick with session_start(). Do not configure the session in any way.

 

You now need to determine if this is a new session or a continuance of a currently existing session. This can be done by checking to see if there are any variables stored in the session - if there are, then this is a continuation of currently existing session. If there aren't then a new session has been started and doesn't have any variables set. This can be achieved firstly by using the isset() function. SO, so far we would then have:

<?php session_start();
  if ((isset($_SESSION['user'])) && ($_SESSION['user']!='')) //checks if session variable 'user' is set and not empty    
  {

At this stage it is only fair to tell you that if you want to allow a person to exit from their browser (i.e. close the program) and then re-open it a while later and still be logged in if they visit the page - then you will have to use 'standard' cookies. Research setcookie() for PHP 'standard' cookie handling. A 'session' cookie will most likely be lost under such circumstance - whereas a 'standard' cookie won't.

 

So the next thing is to grab the session variable 'user' (which could be checked against a database to ensure it exists - but we'll leave that for the moment). So, the code so far, will check for a session and if it exists will assign the value of it to a php variable.

<?php session_start();  
if ((isset($_SESSION['user'])) && ($_SESSION['user']!='')) //checks if session variable 'user' is set and not empty     
{ 
  $username=$_SESSION['user']; //save the value of the session variable 'user' in the PHP variable $username
  $user_session_lives = true;  //set a flag to say that session is still 'live'
  }
  else
  { 
  $user_session_lives = false; //set a flag to say that session has expired OR doesn't exist
  }

SO that is the basics of sessions. The other parts you were using - specifically the last access stored in the session - don't apply unless you are then storing that information in a database and checking it when the user returns OR if you are storing it in a 'standard' cookie. You are storing it in a 'session' cookie which is a bit pointless as if the session is lost (expires or user clears/exits browser) then that information is destroyed - so you can't use it to determine how long ago they were logged in for instance, but as with the $_SESSION['user'], it can tell you whether they still have an active session. However as you can already tell this by the fact that $_SESSION['user'] exists this isn't serving any purpose as a 'session' variable - but would/could as a 'standard' cookie - set with setcookie() (http://php.net/manual/en/function.setcookie.php).

 

I was going to explain a little more - but it's late now and I'm feeling a little sleepy. However, I hope I've managed to help you understand the use of sessions, understand the two types of 'cookies' and which is applicable for what. I'd advise (as other contributors to this page have already done so) that you learn to work systematically. Start with the foundation blocks and then slowly increase the complexity once you've thoroughly understood the core you have built. Adding random bits of code just gives you more issues to sort, but doesn't necessarily solve the issue you originally added them for in the beginning. Start with the simple session management, then add the 'standard' cookie stuff. 

 

Good luck.

Link to comment
Share on other sites

A few comments for clarification:

 

You must not store the user ID or username in a cookie in order to identify the user. Cookies are managed by the client, so they can easily be modified. Nothing prevents a malicious user from changing the name to “admin”, and if your application now thinks the user is an admin, you obviously have a problem.

 

This is why sessions take a different approach: PHP generates a long random session identifier pointing to a session file on the server. The actual session content is kept in that file and cannot be directly modified by the user. The user only gets a cookie with the session identifier. Sure, they could modify their session identifier, but this won't get them anywhere. The chance of finding a valid ID from another user is effectively zero (assuming a proper PHP configuration).

 

So data which isn't supposed to be modified directly may only be stored in the session, not in a plain cookie.

 

It's also not true that sessions are terminated when the user closes the browser. This is just the default behaviour of the session cookies (not the sessions itselves), so both you and your users are free to change this: You may modify the session.cookie-lifetime setting in your php.ini so that the cookies are not destroyed on browser exit. And even if you don't do that, the user may override the cookie lifetime locally or simply restore the cookie when it gets deleted. The session itself is still perfectly valid.

Link to comment
Share on other sites

I've got a little bit of time...

 

Wow that was great. So thorough! Yeah I have that problem of jumping too soon before I can stand. 

 

That's great, the remember me part is nice for future applications

 

I think the 'standard' cookie is what I am after for the mobile aspect where a person switches browser pages

 

I don't see this 'standard' cookie, literally the word 'standard' is that colloquial?

 

I'm looking at this page http://php.net/manual/en/function.setcookie.php

 

Some people have phones that can multitask eg. split screen top/bottom which can view both simultaneously but I assume most people (including myself) don't have that ability maybe Windows 9

 

Okay I will apply what you have written, thank you very much

 

I like that check exist aspect as well

 

Come to think of it, people can't really log out if they wanted to yet haha oops... at least they are logged out anyway eg. session is lost with the current setup but I'll create a log out button.

 

I was concerned about the save path, it did seem counter-intuitive to store a secret thing in a public place

Edited by moose-en-a-gant
Link to comment
Share on other sites

Before you make a big mistake, please also read my comments in #20.

 

Cookies are not a replacement for sessions and will never be, because they can be modified by the client. This remember-me stuff is also very problematic and difficult to implement correctly. I'd say that 99% of the example code you find online is plain wrong and will blow up your entire user authentication.

 

So, please, don't just start implementing some idea that sounds good. If you go beyond standard sessions, make sure you know exactly what you're doing.

Link to comment
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.