Jump to content

The $_SESSION Variable - Who Owns It? Where Is It Stored?


iwato

Recommended Posts

BACKGROUND:  Ever since I realized that the $_SESSION superglobal  was the future of my podcast page (two-three days ago) I have been diligently exploring the PHP SESSION extension.  It is amazing what I discovered.  In particular, I am impressed by the tenacity of a user created session and the associated $_SESSION superglobal.  Indeed, using the session_write_close( ) function one can not only close a browser window, quit one's browser, open the same page in a new browser, but one can also reboot one's machine, and still, the values of the session variables contained in the $_SESSION superglobal associated with the user_created session are in tact.

QUESTION:  To where does the session_write_close( ) function write such that it is forever saved, and how does one purge that location short of destroying the entire file, if the location's contents are not unique to the session whose data it is storing?

 

Link to comment
Share on other sites

That's configured in php.ini.  The default is to use file storage, so it creates a text file for each session ID that contains the contents of the session.  This is why you can only store scalar values in the session, and not resources like an open file handle or database connection.  There are also a series of functions that allow you to create your own session handlers, for example you could use those to store all session data in a database.  On the user's computer, and again this is configurable, the default is to use a cookie to send the session ID to and from the server.

Link to comment
Share on other sites

Thank you for responding.

There is a lot having to do with sessions that is configured in php.ini, but a link to a text file that stores session data does not appear to be one of them.  I just checked.  Have you got any other ideas as to where the data is stored?

Roddy

Link to comment
Share on other sites

It depends on how the session is specified and how the session is ended.

If the session is user-defined, and the session is closed using the session_write_close( ) function, the session variables and their values remain for future use.

How important are they?  I am not sure yet and am still exploring as I always do when confronted with an extension that I have never used before.  It is part of the learning experience.  It started in Thailand way back in 2010, and I cannot rid myself of the habit.  I like grammar!

Roddy

Link to comment
Share on other sites

The location of the files is also configured in php.ini, in session.save_path.  On our servers, for example, it stores session files in /var/cpanel/php/sessions/ea-php56 when the account is running PHP 5.6.  

This is not significant to a PHP programmer though, it's not important how the data actually gets stored unless you're trying to write your own session storage handler (and the vast majority of programmers have no reason to do this).  The important part is that it works.

Link to comment
Share on other sites

Yes, the session.save_path directive is present, but in my configuration it is commented out.  Still the information contained in the $_SESSION superglobal is being saved somewhere.  How would you recommend that I discover where the information is kept.  Running the session_save_path( ) function does not reveal the location.

Also, please read this quote from W3Schools and then my original entry.  My observation appears to contradict W3Schools.   Can you explain why?

Quote

Session variables solve this problem by storing user information to be used across multiple pages (e.g. username, favorite color, etc). By default, session variables last until the user closes the browser.  webpage

Roddy

Link to comment
Share on other sites

All options have multiple ways to get set, and a default.  You can create a phpinfo page to check the local and master values of every setting.

Also, please read this quote from W3Schools and then my original entry.  My observation appears to contradict W3Schools.   Can you explain why?

They describe the default behavior, your configuration might differ.  That will be the session.cookie_lifetime option.

http://php.net/manual/en/session.configuration.php

Link to comment
Share on other sites

It is the php.info option that I checked first.

The session.cookie_path directive indicates local and master values of /.

The session.save_path directive indicates no value for both the local and master settings.

My session.cookie_lifetime option is set to 0 -- likely the default.

Now, I know what a session.save_path file looks like in a directory, as I created two on the fly using the session_save_path() function.  They always begin with the prefix "sess" -- for example,  sess_n1kto7vp86c9nr8po7rl99im03.  In contrast, I have never seen a cookie txt file and do not know what to look for.   Am I correct to assume that the forward slash refers to the top level of my machine?

Roddy

Link to comment
Share on other sites

The cookie path is not a path on your computer, it is a path on the domain on the website.  You can restrict cookies to only being sent to a site if you're browsing under a certain path.  It has nothing to do with local storage of cookies.  If the session.save_path is empty I'm not sure where it would save session files, I would guess it would be in the same directory as PHP.  If you want to look at a browser's cookies the best way is to use the browser's tools, there's a way to search for and delete and maybe modify cookies.  Where and how the browser chooses to store that data is up to the browser, I don't think that behavior is defined by any specification.

Link to comment
Share on other sites

OK, if I have understood properly, ...

1) Cookies are stored on host server, but can be accessed by users via their web browsers.

2) I looked in the directory that houses my PHP application but could find nothing that resembles a place for stored session variables.  Using the session_save_path() function I am able to direct their storage to a specific address and retrieve the information via the session name -- well, at least, I appear to have achieved this ability.  I am not sure under what conditions it works and does not work.

More importantly, I am not sure how to get this command to work on a third party's machine.

Roddy

Link to comment
Share on other sites

No, cookies are stored on the browser machine, not the server.  The server tells the browser to set cookies with particular data, and the browser will send the cookies back to the server on later requests.  That's how sessions work in PHP, PHP tells the browser to set a cookie containing the session ID, and the browser sends the session ID cookie back to the server so that PHP can look up that user's session data, which is saved on the server.

I looked in the directory that houses my PHP application but could find nothing that resembles a place for stored session variables.

That was just a guess on where it saves session data if that path is blank.  I don't know what happens if it's blank, I always set it to a location which I know works instead of leaving it blank.  If you want to look for a particular session file, you can get your session ID from the cookie and search for a file with the session ID in the filename.

I think you're looking too deeply into this.  If you want sessions to work in PHP then all you need to do is use session_start at the start of each page, and then set or get values in the $_SESSION array.  That's all you have to do.  The only time I use session_write_close is if I'm doing a redirection and want to make sure that the session is written before I redirect the browser, otherwise it gets automatically written and closed after the code finishes.  So you don't need to manage a lot of things like this to use them, you can just use them.  If you're managing your own server then you also need to make sure that PHP is configured correctly.

Link to comment
Share on other sites

 

Quote

JSG - No, cookies are stored on the browser machine, not the server.  The server tells the browser to set cookies with particular data, and the browser will send the cookies back to the server on later requests.  That's how sessions work in PHP, PHP tells the browser to set a cookie containing the session ID, and the browser sends the session ID cookie back to the server so that PHP can look up that user's session data, which is saved on the server.

How is it that a cookie can be set in a browser, but the cookie is, itself, not on the same machine as the browser?  Is a cookie not simply a name for special information that is passed between a remote server and a local browser?  If so, how is it that this information cannot be found on the user's machine?

Quote

JSG - If you want to look for a particular session file, you can get your session ID from the cookie and search for a file with the session ID in the filename.

If the session_save_path($path) function is called before the session_start() function, the session variables contained in the $_SESSION superglobal are surely retrievable.  This I have done. But, ...

1) What happens when the user has cookies turned off (session.use_cookies = 0)?  Does this mean that each time the session_start() function is called a new session_id is generated?

2) If item 1) is true, can one use the session_encode() function to transfer the information via a $_GET variable?  Exactly how is this done? 

Roddy

Link to comment
Share on other sites

2 hours ago, iwato said:

How is it that a cookie can be set in a browser, but the cookie is, itself, not on the same machine as the browser?  Is a cookie not simply a name for special information that is passed between a remote server and a local browser?  If so, how is it that this information cannot be found on the user's machine?

The cookie/session that is being set in the browser is only an identifier. The browser sends the identifier back to the server for PHP to retrieve the data for that identifier(cookie/session data) which is on the server. 

Basically what JSG meant here: 

10 hours ago, justsomeguy said:

PHP tells the browser to set a cookie containing the session ID, and the browser sends the session ID cookie back to the server so that PHP can look up that user's session data, which is saved on the server.

 

Link to comment
Share on other sites

How is it that a cookie can be set in a browser, but the cookie is, itself, not on the same machine as the browser?

What?  The cookie IS on the same machine, that's what I was describing.  In fact, that's the only place it is.  The server does not store cookies, the server tells the browser to store cookies.  And the session data is not stored in a cookie, in fact you can use sessions in PHP without using cookies at all.  The only thing that PHP uses cookies for with sessions, if it is enabled, is to tell the browser to save the session ID.  Then the browser can send the session ID back to PHP so that PHP knows which session to open for that user.  

1) What happens when the user has cookies turned off (session.use_cookies = 0)?

First, session.use_cookies is not a setting for the user, that's a setting for the PHP server.  If the sessions are configured to use only cookies (which is better in terms of security), and the user has cookies completely disabled in their browser, then they won't be able to log in or whatever else your sessions support.

Does this mean that each time the session_start() function is called a new session_id is generated?

It would, yes.  As far as PHP is concerned in that case, each request is from a different user.  In my experience, this is rare.  Cookies are used so often that most people generally don't just completely disable them.

2) If item 1) is true, can one use the session_encode() function to transfer the information via a $_GET variable?  Exactly how is this done?

I had to look that function up because I've never used nor heard of it.  Hopefully that tells you something about this.  If you're passing raw session data around through the URL, or there is any other possible way for a user to directly modify their session data, then your application has major security problems.  In fact, you really have no security at all in that case.  I'll just go up to the URL and change my username to "admin", and change any permissions I see, and now I'm whoever I want to be in your system.  That's not good.  Don't worry about trying to manually pass session data.  As a programmer, when dealing with sessions, you have 2 jobs.  One of them is to use session_start at the beginning of every page, and the other is to save and read certain data in $_SESSION.  If you're trying to figure out the details about how the server is saving the session data then I hope those questions are only academic, because it doesn't matter unless you need to use a custom session save handler for some reason.

Just as an example - this code should absolutely not be used today - here's a post I made from 2006 showing custom session handlers using a database.  This code is super old and full of bad practices, but I'm showing it just as an example of when you might do anything other than just using session_start, the $_SESSION array, and maybe session_write_close before a redirection.  

http://w3schools.invisionzone.com/topic/9731-custom-session-save-handlers/

 

Link to comment
Share on other sites

Quote

JSG - The only thing that PHP uses cookies for with sessions, if it is enabled, is to tell the browser to save the session ID.  Then the browser can send the session ID back to PHP so that PHP knows which session to open for that user.

I did notice that session IDs are stored in the $_COOKIE superglobal when cookies are turned on.  This suggested to me that Cookies and Sessions are used together.  You have now provided me with an important use that explains why web masters often tell their users to leave cookies turned on.

QUESTION:  So, how is this done?  I would very much like to have my users return to the last place they visited without having to log in.  This is what I have understood.  Please confirm or disconfirm each of the statements.

1) The session_start() function generates automatically a session ID that is stored on the server.

2) If a cookie is set, when a session is begun, the session data from a closed session can be retrieved via the session ID stored on both the user's machine and the server, but only if the session data are stored on the server.

3) If cookies are turned off, the session ID will not be stored on the user's machine, but it can be stored along with all of the session data on the server using the session_write_close() function.

4) If the session_write_close() is not employed the session data will be lost at the end of the session.

5) If a session ID is saved on a server, then it can be assumed that the session data related to that ID are also saved.

6) The session ends when the browser is closed, or at least, all of the tabs with webpages containing the session_start() function are closed.

7) If the session_write_close() function is employed, the value of the session variables just before the function is called can be retrieved via the session_id() function that was in use when the data was saved.  However, only the last $_SESSION update is stored and retrievable unless manually set to do otherwise.

Now, under the assumption that the user has cookies turned on, how does the browser know to invoke the proper session ID when the user returns to the same webpage.  Is the latest session_ID automatically sent by the browser to the server?  Or, must it be invoked to do so.  If this latter is true, how is the transmission invoked?

Quote

JSG - If the sessions are configured to use only cookies (which is better in terms of security), and the user has cookies completely disabled in their browser, then they won't be able to log in or whatever else your sessions support.

With regard to the security issue: under the assumption that session data are automatically destroyed with the close of each session, if they are not manually saved before the end of the session how could not employing cookies be less secure?  Or, is it because the session data are automatically saved when a cookie is set?

Link to comment
Share on other sites

Quote

The session_start() function generates automatically a session ID that is stored on the server.

If sessions are set up to only use cookies, then the session ID is stored in the cookie, and either used as part of the filename (if the default session file handling is enabled) or otherwise saved so that the server can look up a session by ID.

 

Quote

If a cookie is set, when a session is begun, the session data from a closed session can be retrieved via the session ID stored on both the user's machine and the server, but only if the session data are stored on the server.

 

If the session has not expired and been deleted then the session ID should point to the session data.

 

Quote

If cookies are turned off, the session ID will not be stored on the user's machine, but it can be stored along with all of the session data on the server using the session_write_close() function.

 

If cookies are turned off then the session ID can be passed around through page URLs, but that is terrible security.  PHP should be configured so that sessions.use_cookies is on, and sessions.use_only_cookies is on.  It's also good to have sessions.cookie_secure on if your site uses HTTPS, and sessions.cookie_httponly on.  Session_write_close isn't really affected by whether or not cookies are being used.  The only time that cookies have any effect on that kind of thing is if you're starting a session for the first time and also redirecting, sometimes I've seen the browser fail to set the session cookie but that was years ago, I assume that browsers have improved since then.

 

Quote

If the session_write_close() is not employed the session data will be lost at the end of the session.

 

Not true.  Like the manual says:

Quote

Session data is usually stored after your script terminated without the need to call session_write_close()

Quote

If a session ID is saved on a server, then it can be assumed that the session data related to that ID are also saved.

That's kind of a weird statement.  I'm not sure what the point is.

 

Quote

The session ends when the browser is closed, or at least, all of the tabs with webpages containing the session_start() function are closed.

 

The browser is supposed to delete the session cookie when it closes, because it is a temporary cookie.  The session expires after a period of inactivity matching the PHP settings.

 

Quote

If the session_write_close() function is employed, the value of the session variables just before the function is called can be retrieved via the session_id() function that was in use when the data was saved.

 

That's also phrased a little strangely, again I'm not sure what you're getting at.  Normally you never need to use session_write_close.  Like the manual says, the only thing it helps for is if you have multiple pages all loading inside different parts of a frameset, and in each one you would want to close the session as soon as that page is finished with it so that the other pages can open the session and run.  It is not normal for the vast majority of scripts to use session_write_close.  Also, the session_id function is not used to get session data, its only purpose, like the manual says, is to either get or set the current session ID.

 

Quote

Now, under the assumption that the user has cookies turned on, how does the browser know to invoke the proper session ID when the user returns to the same webpage.

 

The browser doesn't know anything about sessions.  The browser doesn't know what a "session" is, and it has no idea that PHP is a thing.  The browser just sends cookies, cookies have been a part of the HTTP specification for a long time and PHP decided to use cookies to help support sessions in PHP.  All the browser does is save and send cookies just like it does with any other cookie.  If you want to know how cookies work in general, there should be a lot of documentation for that.  When cookies are set they include the domain name and path, and some other settings, and if the browser requests a page which has matching cookies then it sends those cookies when it makes the request.  Cookies are sent as part of the HTTP headers.

 

Quote

Is the latest session_ID automatically sent by the browser to the server?

 

The browser sends any cookie the server told it to set, as long as the cookies match the URL that the browser is requesting.

 

Quote

how could not employing cookies be less secure?

 

Regardless of how session data is saved or destroyed, it's less secure because the alternative is to pass the session ID in the URL, and now anyone watching traffic can look at your URLs and hijack your session.  Or if you copy and paste a URL to someone else, and don't know about something like a session ID, then that other person clicks the link and now they're logged in as you.  There are any number of ways where passing the session ID in the plain-text URL might bite you in the butt.  As long as your site is using HTTPS, then the headers sent by the browser and server are part of the encrypted data, so all anyone snooping on your traffic can see is the URL.  They can't see any of the data payload, just which page you're requesting.  Everything else is encrypted.

  • Like 1
Link to comment
Share on other sites

JSG:  I would like to thank you for your kind response.  It was very informative.  It did, however, raise some new questions, and there were one or two points that still need clarification.  Please consider the following and confirm or disconfirm each statement as before:

1) As each webpage is a different address the cookies associated with each page are different. Thus, during a session at least one setcookie() function must be called on each page where a call to the session_start() function is made?

By the way, is this the way in which sessions are made secure with cookies?  Or, is something additional required?

2) QUOTE: If a session ID is saved on a server, then it can be assumed that the session data related to that ID are also saved.
JSG:  That's kind of a weird statement.  I'm not sure what the point is.

I asked this question because I am unsure about the relationship between the session ID and the session data.  The session ID appears to be an address for the session data on the one hand, and a means of communication between a browser and the server via cookies on the other.

3) There appear to be five, certainly three, different setting in the php.ini file that are related to time including
    session.cache_expire = 180  (The session data will continue to be available three minutes after the browser is closed.)
    session.cache_limiter = nocache
    session.cookie_lifetime = 0 (The cookie associated with the current session disappears when the session expires (see above))
    session.entropy_length = 32
    session.gc_maxlifetime = 1440

Could you also provide insight with regard to the other three?

4) QUOTE: The session ends when the browser is closed, or at least, all of the tabs with webpages containing the session_start() function are closed.

JSG:  The browser is supposed to delete the session cookie when it closes, because it is a temporary cookie.  The session expires after a period of inactivity matching the PHP settings.

This suggests that there are two kinds of cookies:  session-related cookies and session non-related cookies.

If the above is true, are there separate settings for each?

Also, please make the following clear.  Is it the closing of all pages that have called the session_start() function that closes the session, or is it only the closing of a browser that forces a session to end.

5) JSG:  [T]he session_id function is not used to get session data, its only purpose, like the manual says, is to either get or set the current session ID.

Yes, but is it not the getting of the session ID that makes the values of the session variables available?
 

 

Link to comment
Share on other sites

As each webpage is a different address the cookies associated with each page are different.

Not necessarily.  You can specify that a particular cookie should only be used on a specific URL, but you can also specify that a cookie should be sent to any URL on a domain and any of its subdomains.  The default for session cookies is any URL.

Thus, during a session at least one setcookie() function must be called on each page where a call to the session_start() function is made?

Setcookie is not used for sessions.  The only function you need to call to use a session is session_start.  It's literally the only function you need to use, unless you have some need to change the cookie settings on a particular page for some reason, or you want to regenerate a new session ID every time, or something like that.  Otherwise, you call session_start, then you use $_SESSION.  It's not any more complicated than that, you don't have to know anything at all about cookies if you want to use sessions, as long as PHP is configured correctly.

By the way, is this the way in which sessions are made secure with cookies?  Or, is something additional required?

I mentioned some settings in my previously reply that can help secure session cookies.  Those are all changes that are made to the PHP configuration, it shouldn't be necessary to do any of that in the code unless you're on a shared host or something where they're using an insecure setup that you can't otherwise change.

I asked this question because I am unsure about the relationship between the session ID and the session data.  The session ID appears to be an address for the session data on the one hand, and a means of communication between a browser and the server via cookies on the other.

It's just an ID, it tells the server which session belongs to the user.  If the default file handling is used for sessions, and you send PHP a cookie saying that the session ID is "123", then it's going to prepend that with whatever the configuration says, typically "sess_", and then look for a file in the directory defined as the session storage location.  So, for example, it might look for a file called "/tmp/sess_123", and if that file exists and is readable then PHP will open it and attempt to read the data in the file, which is the session data.  If the file doesn't exist then PHP will create it and store any session data there.  So it's just an ID, an identifier, it's not an address or means of communication or whatever, just an ID.  There's also no requirement about how the ID is used, if I want to make a custom session handler and instead of using files I open a socket to my internet-connected toaster and have it eject a piece of bread at my smart refrigerator which causes it to look in the produce tray and see if there's a stalk of celery in there that has the session ID printed on it, PHP doesn't care as long as the internal functions for opening a session, reading session data, writing session data, closing a session, etc all work.  If you're looking for a specific implementation that every instance of PHP uses, you won't find one.  The default for session handling is PHP's internal session file handling, but you can write your own session handler to get the ID from PHP and read/write session data.  You can have it use a database, or carrier pigeons, or whatever implementation works for you, as long as it works.  The default file handling is used most often because it's generally fast and easy and relies on the automatic garbage collection of the operating system to periodically delete files from the /tmp directory so they don't pile up.  There might be certain file systems that aren't good at dealing with a lot of small files, in which case maybe you want to use a database on that server, as long as the database connection overhead doesn't slow things down more than the filesystem does.

Don't think too much about the fine details of this stuff.  It's all just academic at this point, the programmer does not have to deal with those things.  Don't lose the forest for the trees.

Could you also provide insight with regard to the other three?

All of the configuration options are described in the manual, for example:

http://php.net/manual/en/session.configuration.php#ini.session.gc-maxlifetime

If you don't understand an explanation, let me know what you don't understand about it.

This suggests that there are two kinds of cookies:  session-related cookies and session non-related cookies.

If the above is true, are there separate settings for each?

I'm not sure what you mean.  There's only 1 kind of cookie as far as browsers and servers are concerned.  The session cookie in PHP is just another cookie, like any other cookie, with all of the same options available to it as any other cookie.  You can configure the settings for it just like you can configure the settings for any other cookie you want to set.

Also, please make the following clear.  Is it the closing of all pages that have called the session_start() function that closes the session, or is it only the closing of a browser that forces a session to end.

I don't know, it's probably left up to the browser vendors on how to handle that, I doubt that behavior is defined so specifically by any specification.  It wouldn't matter if the session_start function is used, because again the browser doesn't know anything about PHP.  What would probably matter is if the browser has anything open to a URL that matches the settings for those cookies.  But I don't know if they will immediately delete temporary cookies just when the tabs to those URLs have been closed, or if they wait until the entire application is closed.  I assume it's the latter, because vendors probably think that someone might have mistakenly closed a page, and they would expect that if they open the page again then their session is still active.  Browser vendors probably think that would make more sense to a user.

Yes, but is it not the getting of the session ID that makes the values of the session variables available?

Yeah, one of the steps in the process is to get the session ID, but that doesn't mean that the session_id function is the only step in the process.  The role of the session_id function is only to get or set the current session ID, not get any session data.  Other functions do that.  Moreover, the programmer does not need to call session_id manually if all they're trying to do is get the session data, all they have to do, again, is call session_start.  Everything else is handled behind the scenes.

Link to comment
Share on other sites

I don't know how the recent forum update gets parsing so wrong, but this is what I had for that last part, I didn't have any nested quotes.

Quote

This suggests that there are two kinds of cookies:  session-related cookies and session non-related cookies.

If the above is true, are there separate settings for each?

I'm not sure what you mean.  There's only 1 kind of cookie as far as browsers and servers are concerned.  The session cookie in PHP is just another cookie, like any other cookie, with all of the same options available to it as any other cookie.  You can configure the settings for it just like you can configure the settings for any other cookie you want to set.

 

Also, please make the following clear.  Is it the closing of all pages that have called the session_start() function that closes the session, or is it only the closing of a browser that forces a session to end.

I don't know, it's probably left up to the browser vendors on how to handle that, I doubt that behavior is defined so specifically by any specification.  It wouldn't matter if the session_start function is used, because again the browser doesn't know anything about PHP.  What would probably matter is if the browser has anything open to a URL that matches the settings for those cookies.  But I don't know if they will immediately delete temporary cookies just when the tabs to those URLs have been closed, or if they wait until the entire application is closed.  I assume it's the latter, because vendors probably think that someone might have mistakenly closed a page, and they would expect that if they open the page again then their session is still active.  Browser vendors probably think that would make more sense to a user.

 

Yes, but is it not the getting of the session ID that makes the values of the session variables available?

Yeah, one of the steps in the process is to get the session ID, but that doesn't mean that the session_id function is the only step in the process.  The role of the session_id function is only to get or set the current session ID, not get any session data.  Other functions do that.  Moreover, the programmer does not need to call session_id manually if all they're trying to do is get the session data, all they have to do, again, is call session_start.

  • Thanks 1
Link to comment
Share on other sites

OK.  Let's pause here while I engage in some implementation.

 I believe that I have sufficient grasp of the matter to produce something that can be useful to my users.

Thank you for both your patience and assiduous insight.

Roddy 

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...