PDA

View Full Version : Session Variables


Horus_Kol
09-30-2002, 11:46 AM
Can someone explain to me the concept behind session variables?

I am after -

What?
Why?
and Where?


Thankyou,
the Eagle-headed dud

rdove
09-30-2002, 12:09 PM
Session variables (or atleast in my opinion) are like global variables. You can use them to declare variables that you may need to access on multiple pages. Generally I use them in login pages and I store the user name. The difference between a session variable and a cookie is that session variables are only available for a certain time period. Usually a session timeout is 15 minutes unless you set it differently or until the browser is closed. You can set a session variable anywhere on a page (atleast in ASP you can).

Dr. Web
09-30-2002, 12:17 PM
sure.

Session variables can track a user for the life of their visit to your site. Sessions variables can exist on the server (most likely) or on the users pc, for the life of the session... or visit to the site. They are used to store information. What information? Whatever you want. Probably easier to look at an example, huh?

So, I login to HTML forums. I have used my username and password, and I want to be able to navigate page to page without re-logging in. So, Vbulletin assigns me some session variables on the webserver that look like this:

user: 3827987
loggedIn: 1
authorityLevel: 2

And those variables would mean:
user: a unique number identifying me in the database of users. Useful if they want to retreive my name or personal info at any point.
LoggedIn: 0=not logged in, 1=yes logged in.
authorityLevel: 0=none, 1=general user, 2=moderator, 3=admin

So, now that we have server side persistant variables (which auto destroy after about 20 minutes of inactivity) I can surf through the site without relogging in at each page... because you see, when I try to post a message or access the moderator functions-vbulletin will need to verify that I have the correct loggedIn status and authorityLevel. Each of these 'protected' features looks for the existance of such session variables... if they are present (and at the correct level) I get access, if not I am prompted to login (or told that I don't have the proper authority).



There is ususally a limit to how many session variables that you can store...I think coldfusion has about 15. You shouldn't store sesitive information like cc numbers, phone numbers, logins, passwords and so on in these. They should be the bare bones of what the application needs to identify the user, and get into a database for more info. So, by storing my user number in a session variable you can do a db query to find out who I am, my name, location, all my posts etc.

Dr. Web
09-30-2002, 12:18 PM
ryan, session variables are simply SERVER SIDE COOKIES with expiration date/ times attached.

scoutt
09-30-2002, 12:51 PM
they dopn't auto destroy in 20 minutes. they get destroyed when you close the browser. or I guess you can set the server up so they can be destroyed but this place isn't like that and most I have seen aren't.

but yes the session are serverside cookies.


did you read the php manual Horus, they explain it pretty good.

Horus_Kol
09-30-2002, 03:12 PM
I guess I should have posted in the server side one.

I am asking because I am having trouble with an ASP file. One of the session variables is staying null. The annoying thing is, it is fine on other servers at work.

I got confused because I have never seen an ASP file before, and most of the code appears to be written in JavaScript.


php manual -there's an idea. I am sorry to say that I can't really think well just before it is time for me to go home from work. :P


Edit:
oh - so not with it. I thought I had put this in the client side forum

Dr. Web
09-30-2002, 03:29 PM
Originally posted by scoutt
they dopn't auto destroy in 20 minutes. they get destroyed when you close the browser. or I guess you can set the server up so they can be destroyed but this place isn't like that and most I have seen aren't.

but yes the session are serverside cookies.


did you read the php manual Horus, they explain it pretty good.


that is not correct scoutt. I often accidentially close HTML forums down, and open a new browser and and am still logged in, and the same "new" messages are marked new. The place to set up your session timeout is on the global.asa file (asp) or in the application page in coldfusion.

In fact, most Serverside session variables (cookies) Do in fact have an expiration time that auto expire. They update on each page view, and the default is usually 20 minutes.

Dr. Web
09-30-2002, 03:33 PM
horus,

heres a page helping out with ASP session variables:
http://www.w3schools.com/asp/asp_ref_session.asp


and just for scoutt, here is the asp page showing how to change the DEFAULT of 20 min timeout to 30 minutes in asp:

http://www.w3schools.com/asp/showasp.asp?filename=demo_gettimeout

you can check your php session default life here:

http://php.he.net/manual/function.session-get-cookie-params.php


and in coldfusion you would: (default 20)

SESSIONTIMEOUT=#CreateTimeSpan(x,x,x,x)

BTW, asp can be written in server side javascript, or server side vbscript. There are some differences, but if your an old hand at javascript, you'll understand most of it.

rdove
09-30-2002, 03:57 PM
ryan, session variables are simply SERVER SIDE COOKIES with expiration date/ times attached.

I don't know why I didn't finish my comparison thought for some reason. I meant to say something along the lines of the difference between Session variables and cookies is that when you close the browser the session is terminated whereas with cookies the browser will "re-enter" the information for you when you visit the site again.

Sorry for not being clear on what I was trying to say.

scoutt
09-30-2002, 05:14 PM
Originally posted by Dr. Web
that is not correct scoutt. I often accidentially close HTML forums down, and open a new browser and and am still logged in, and the same "new" messages are marked new. The place to set up your session timeout is on the global.asa file (asp) or in the application page in coldfusion.

In fact, most Serverside session variables (cookies) Do in fact have an expiration time that auto expire. They update on each page view, and the default is usually 20 minutes.
bet me: :D

I know you can set the server up to auto expire, but this place doesn't. I can have my browser open all day and not do anything and it doesn't expire. acts like I never left. also vBulliten saves the session ID in mysdql so the cookies are what actually open the sessions and then starts like you never left. I never log out and always just shut down the browser. most sites that run vBulliten are like this.

By default:
php's session.cookie_lifetime specifies the lifetime of the cookie in seconds which is sent to the browser. The value 0 means "until the browser is closed." Defaults to 0.

PHP is setup like that by default. of cource you can change this in the php.ini file with ini_set() but generally that is only for the page that is being viewed and not the whole site.

http://www.php.net/manual/en/printwn/ref.session.php#AEN78724

that is teh page you wanted to link to :P

Dr. Web
09-30-2002, 07:41 PM
"I know you can set the server up to auto expire, but this place doesn't."


yes, because you are logged in with a cookie saved to your computer. However, your SESSION, which is a different cookie is saved on the webserver either in memory or in db. For instance, when I go to this site, I NEVER login. Thats because I've opted to remain logged in via a cookie. All that really means is that there is a cookie on my pc that allows vbulletin to auto log me in when I hit page1, and create session variables at that time.

Once session variables are created, they live for about 20 minutes if the user is inactive. For instance, hit the site, and see all the "new posts" lighbulbs. They will remain lit as you surf through the site to let you know whats new and so on. Now, hit the site but DONT surf, wait 26 minutes without doing anything and then refresh the page. ALL the "new post" lightbulbs are gone. Why is that? Because vbulletin shows "new" messages.... messages since your last session... and your last session just expired.

Finally, open a browser, hit htmlforums and notice all the "new message" lightbulbs. Close your browser. Open a new browser and goto htmlforums. Same lightbulbs are lit. Why? becuase your session (which is living on the server) is still alive even though your browser session ended.

Dr. Web
09-30-2002, 07:47 PM
Scoutt, I'm not trying to be rude, but did you read that page that you sent me? :D

"session.gc_maxlifetime specifies the number of seconds after which data will be seen as 'garbage' and cleaned up"
session.gc_maxlifetime "1440" PHP_INI_ALL

which is 1440, or 24 minutes. I've already shown you the 20 min default of ASP. So, I was off by 4 minutes in php? Okay, I can deal with that because the concept is secure.


and here is the DEFAULT path on the webserver that php uses to store session data:

session.save_path "/tmp" PHP_INI_ALL

"session.save_path defines the argument which is passed to the save handler. If you choose the default files handler, this is the path where the files are created. Defaults to /tmp. If session.save_path's path depth is more than 2, garbage collection will not be performed.

Warning: If you leave this set to a world-readable directory, such as /tmp (the default), other users on the server may be able to hijack sessions by getting the list of files in that directory. "


In fact, even though the PHP doc says that the session is stored on the users pc, I can close IE (on my laptop), hit HTMLForums from a totally different PC (one of my test machines) and STILL get the same "new posts" that I just saw on my laptop. If the session was destroyed when I closed IE(on my laptop), then I wouldn't see but maybe one "new post" lighbulb. Thats interesting.

It tells me that the session data is maintained in the /sessionData (or whatever it is) directory on the webserver, and in the event of no cookie present on the users machine/ browser, it looks in the /sessionData directory for a session for that user. If there is a session cookie there, it assigns to to the user... thus preserving their session ACROSS machines and ACROSS closed browser sessions.

I just physically did this excercise. Worked like a charm. Even at home, sometimes I'll get a blue screen... have to reboot... and I STILL get the same session as long as I can get online in less than 20 (or 24) minutes.

scoutt
10-01-2002, 12:20 AM
Doc I understand what you are trying to say, but I have to say php is not like that. the forums save your session in the DB and the time. that is where the light bulbs come on, they are set to a time, nothing to do with a session time but the time you logged in and also the time the post was created and how long that time is set to show the lit bulb and then a dimmed bulb. nothing to do with sessions.

when the browser closes it deletes the session (well tries to but that is why the cleanup) when you open your browser again you get a NEW session ID. it gets the variable from the cookies stored on your computer and then adds them to the sessionID the browser created.

actually think about it, session.gc_maxlifetime specifies the number of seconds after which data will be seen as 'garbage' and cleaned up this happens after the browser has not updated the session in the maxlifetime time. if you get close your browser you get a new ID everytime, if you sat there for hours and the server cleaned up your sessionId the browser upon refresh makes the same session ID it has in its memory, In the event a valid session ID is given, all of the data associated with that session ID will be reloaded with identical values, and in the exact same state it was in when it was last accessed.
That way you have the same sesion variables but different time as it saves it to the DB. that is also how the who's online works too.

Dr. Web
10-01-2002, 01:49 AM
scoutt,

what do you mean PHP is not like that? I just showed you that it is, right from the php document. the session gets cleaned up (garbage collection) after about 24 minutes, and that the session lives on the server (or a db). How is that not like the session management of any other ss language? IN both CF and ASP you can store session variables in the server memory as well as a db, and you have a default time that the session lives (which may be edited).

As for sessions in vbulletin, why do "new post" light bulbs dim after I let my session expire (25 minutes)? When I don;t login, all forums are lit as "new posts".... even though they are well over some arbitrary limit.

The lightbulbs are lit as "new posts" since my last session, otherwise the lightbulbs wouldn't go dim after my 25 minutes of inactivity/ refresh. If the "new post" lit icon was set to a limit of time past the original post date, all users would see the same "new post" lightbulbs regardless of logging in, or regardless of letting a 25 minute session expire.

torrent
10-01-2002, 06:01 AM
Hi guys,
Are we all having an interesting debate here :D

I'm not going to explicitly agree or disagree with anyone here. I'm just going to post the key characteristics of session management in PHP (it works pretty much the same in any language):

PHP's session management library offers the key characteristics required of a session management library:
It stores session data on the server. Because the library uses different storage modules, you can keep the data in plain text files, shared memory, or databases. The exact location of data is not really important (as long the performance of the medium is sufficient).
It uses a cryptographically random session ID to identify a user.
It saves the session ID (and only the session ID) on the client side using cookies, GET/POST, or the script path.
If the user disables cookies, the application can use other means of session propagation.

Ending Sessions
Ending a session is not automatic. This makes sense as HTTP is stateless protocol and therefore cannot tell whehter a user is "finished" or not. Therefore PHP offers a number of commands to help control session closure
You can force a session to end by using the session_destroy() function. This is useful in the cases where a user logs out
You set the gc_maxlifetime directive to determine how long after the last access the the session data the user should be logged out. The default is 0 which means the session cookie is deleted upon closure of the browser. I have known instances where this does not occur though! NOTE: From my own experiences with this directive is that it does not work on Windows as it relies on a file's atime being updated, which Windows does not support. As it happens PHP is pretty much hosted on Linux servers and so this is rarely a problem.
In conjunction with gc_maxlifetime you should also use a neat directive called gc_probability. This specifies with what probability the sessions should be cleaned up. It's specified as a percentage. If, for example, you set it to 100 (100%) then the cleanup operation executes on every request. If you specify 1% (the default) then the cleanup operation occurs for every 1% of requests. This enables the developer the ability to manage any session clean up overheads instead of being forced to conduct clean up checks for every single request (which you can do if you so wish).Regarding the number of session variables, in PHP there are no specified limits, not sure about ASP. I also do not recommend passing the Session ID using HTTP GET (e.g. in a url query), as the user will be able to effectively bookmark the session. There are ways around this potential security issue which involve the use of gc_referer_check (I think that's what it's called), but better off storing the session ID to either shared memory or a database if cookies are not an option.

Hope this helps somewhat.

Finally, there is one other type of session. Every Firday, when work ends I often (permission from the wife permitting:)) go down to the Pub with a couple of mates for a good session. Unfortunately, the reliability of ending this kind of session as specified by the wife_session_handler is rarely adhered to and more than sessions are destroyed later ;) (potentially impacts another type of session, but we won't go into that one:))

scoutt
10-01-2002, 04:47 PM
sorry I haven't gotten back but I have been running a little test on session Id's. Doc, I ain't disagreeing with you over the fact the gc_maxlifetime deletes the session if it has not been updated in the specified amount of time, I agree on that fact.
what I did was wrote a small script that makes a sesionID and stores the time and name and password in the sesion and then waited for about an hour or 2 and Refreshed the page. the conclusion is what I said in one of my post, the session may get cleaned but the browser loads the exact session ID and all the variables to the server. also after I have logged out and removed the session it comes back to the same session ID. now if I was to close the browser it will create a new ID. actually php creates the ID and just assigns it to the browser.

so the light bulb theory is the same. if you waited on refreshing the page for like 2 hours the DB sees the time in the session and compares it to the time the post was made and if it is over it alloted time it makes the bulb dim. in fact here is teh code that does it.


if ($bbuserinfo['lastvisitdate']=='Never') {
$forum['onoff']='on';
}
if ($userlastvisit < $forum['lastpost']) {
$forum['onoff']='on';
} else {
$forum['onoff']='off';

$bbuserinfo['lastvisitdate'] == DB data that is stored from the session that was just created. so all session variables go into the DB including session ID.

Dr. Web
10-02-2002, 12:44 PM
scoutt,

we are probably agreeing more than we think. The lighbulb theory I said was exactly what you explained: lit for a set time from your last visit, or session.

the php manual writes that the client side cookie contains only the session id, and the server stores the variables in the memory, directory, or db. Now, if the server cleans out the session variables off the server with the use of GC after the 24 minute limit, how will the user get the variables back? All they have is the session id... nothing else, and the server has deleted the session that matches it.

So, it CREATES a new session, with the same ID on the users cookie (albeit updated variables such as timeloggedIn). Now, if you store session variables in the client side cookie then you can get those variables back.

I just haven't seen anything that states that garbage collection (in asp, php, or coldfusion) doesn't happen as a default for session variables stored on the server. Otherwise you would have literally thousands of open sessions at any given time. Probably the easiest way to verify this is by looking into the database of HTMLfourms sessions. Are there thousands and thousands of sessions which users just 're loginto', or are there just active sessions, which get GC cleaned out after 'x' amount of time of inactivity?

Dr. Web
10-02-2002, 12:52 PM
okay, this one will throw you for a loop:

I login to htmlforums, and see 6 lit "new posts" out of all the possible threads. The client side session number is on my pc via a client side cookie, agreed?

Now, I delete all history, tif, and COOKIES from my machine. So technically speaking... I shouldn't be able to get the same session, right? The session id is gone from my machine. So I close IE down, and open a new instance, login to html forums, and what do you think I see?

6 "new post" lightbulbs. In fact, I just cleared out the history, tif, and cookies... closed the browser, and logged in the HTMLForums with a TOTALLY DIFFERENT computer... and I still get the same 'new posts' lightbulbs.

My session is 'alive' on the server in the db, and I can get to it whether or not I have the cookie on my machine, and whether or not I even decide to change machines.

Dr. Web
10-02-2002, 01:06 PM
after looking at coldfusions session db, we store sessions for about 3 months at a time (unless overriden on the application page). So, if my users logout, and log in tomorrow, they get the same session id... but new data (as long as I don't specify to delete the session number).

However, I am storing session variables in my client side cookie (users first and last name, application etc)... so if they delete the cookie, they can get the info back, and it must be recreated. Interesting. However, HTML forums seems to retain my data a little better. Where is htmlforums storing the data? on the client, or on the server....

scoutt
10-03-2002, 11:08 AM
you are correct. if you deleted all your stuff and restarted and logged in you will still get the same lit bulbs as before, becasue your time that is stored in the DB is still less then the lit bulb time or posttime. in theory it should be this way. let me double check in case I missed something in the code.

if you did all that and waited for about an hour or so it would be different. this is the code that htmlforum uses to get session info that is stored in the DB.

$ourtimenow = time();
cookietimeout = 900 //This is the time in seconds that a user must remain inactive before the unread posts are reset to read.
SELECT sessionhash,userid,host,useragent,styleid FROM session
WHERE lastactivity>".($ourtimenow-$cookietimeout)." AND sessionhash='".addslashes($sessionhash)."'
AND host='".addslashes($REMOTE_ADDR)."'
AND useragent='".addslashes($HTTP_USER_AGENT)."'"

and the session ID is in the cookie that is stored on the user.so if you deleted all that stuff it gets the session form the DB, if they don't match itis deleted and then deleted and then put back with the new session ID.

it maybe a littel more complexed than that but I jsut gave a general idea on how it works.

Dr. Web
10-03-2002, 02:53 PM
yep. This is just one of those cases where I'm being stubborn and not realizing that we are agreeing. Good call there Scoutt (and Torrent).

Even still, its quite nice to explore these things deeper on occaision.

scoutt
10-03-2002, 03:16 PM
yup it was real exciting to look into this. I even learned a few more things, forgot my telephone number but it ill come again :)

this forum is more complexed than what I have shown so I touched on the tip of it. still good stuff.

yoda
02-11-2003, 10:42 AM
Q :
what's the correct way:
-session_register($my_name); or
-session_register("username");

i got 'em both from a tut but they explain session reg different
:confused:

scoutt
02-11-2003, 11:17 AM
the correct way and the preferered way

$_SESSION["username"] = $username;

the session_register() is deprecated and shouldn't be used.

karinne
12-11-2005, 07:22 PM
OK... talk about resurrecting a post from the dead ;)

I'm trying to get an online thing going on a site. I use $_SESSION when poeple log in but I don't have a log out page for them 'cause... well... I just know they won't click it half the time.

So... so far, when users log in, I update my db to say that they are logged in. But... since I don't have a "logout" button, how can I know when to change my db to say "logout" ?!?

Any help will be greatly appreciated as always.

BTW... if it was in one of these post and missed, I'm blaming it on my kid ;)

edit: BTW... I just noticed that this was in Server-Side Programming... I'm coding in PHP

scoutt
12-11-2005, 10:26 PM
basically you have to run a script on every page or so to check the db for the time they logged in. if this time doesn't change in so many minutes than log them out. this will also have to have another script to keep updating the time stamp so the other script will see the time change. then you have to update the database accordingly. so when the user logges in it updates the db. then on certain pages you run the other one to keep updating that time. the script that does the update timing will have to do it per ID.

make sense?

karinne
12-12-2005, 10:26 AM
yeah it makes sense... thanks scoutt!