Related
I know there are hundreds of these questions but what I am asking however is slightly different.
When the user logs in I would like to get all their data from each table in a database and store it in a session variable (obviously not sensative data such as encrypted password/salts etc basically data that would be useless or have no value to a hacker!!), and whilst the user uses the website the relevant data stored in the session will be used as opposed to accessing the database everytime. Moreover when the data is changed or added this will be written or added to the session file, and upon a major action such as "saving" or "loggin out" the new/changed data will be written to the database.
The reason I wish to do this is simply for efficieny, I want my application to not only be fast but less resource consuming. I am no expert on either which may explain why my idea makes no differnece or is more resource intensive.
If there is an alternative to my solution please let me know or if there is something to improve on my solution I will be glad to hear it.
Thank you.
My application is using PHP and mysql.
If any of these don't apply to your app, then please ignore. In general, I'm against using sessions as caches (especially if anything in the session is going to be written back to the DB). Here's why.
Editing the session requires a request from the user. Editing a php session outside of the request-response cycle is very difficult. So if a user Alice makes a change which affects Bob, you have no way to dirty Bob's cache
You can't assume users will log out. They may just leave so you have to deal with saving info if the session times out. Again, this is difficult outside of the request-response cycle and you can't exactly leave session files lying around forever until the user comes back (php will gc them by default)
If the user requires authentication, you're storing private information in the session. Some users may not be happy about that. More importantly, a hacker could imploy that private information to conduct a social engineering attack against the end-user.
Mallory (a hacker) might not be able to use the information you put in the session, but she can poison it (ie. cache poisoning), thereby causing all sorts of problems when you write your cache to your permanent storage. Sessions are easier to poison then something like redis or memcache.
TL;DR Lots of considerations when using a session cache. My recommendation is redis/memcache.
You can also go for local-storage in HTML5, check The Guide and THE PAST, PRESENT & FUTURE OF LOCAL STORAGE FOR WEB APPLICATIONS
Local Storage in HTML5 actually uses your browsers sqlite database that works as cookies but it stores data permanently to your browser
unless someone by force remove the data from the browser finding the data files
Or if someone remove/uninstall browser completely,
or if someone uses the application in private/incognito mode of the browser,
What you need to do
Copy the schema for required tables and for required columns and update data at a regular interval
you dont have to worry about user's state, you only have to update the complete data from the localStorage to mysql Server (and from the mysql server to localStorage if required) every time user backs to your application and keep updating the data at regular interval
Now this is turning out to be more of localStorage but I think this is one of the best solution available for me.
redis is a good solution if it is available for you (sometimes developers can't install external modules for some reason) what I would do is either go with your Session approach but with encoded/encrypted and serialized data. Or, which I really prefer is to use HTML5 data properties such as:
<someElement id="someId" data-x="HiX" data-y="Hi-Y" />
which BTW works fine with all browsers even with IE6 but with some tweaks, specially if your application uses jquery and ajax. this would really be handful.
You need to use Memcache for this kind of work. To solve the problem of keeping the updated data everywhere you can create functions for fetching the data, for example when the user logs in you, authenticate the user and after that insert all the user data into the memcache with unique keys like :-
USER_ID_USERNAME for user's username
USER_ID_NAME for user's name
etc...
Now create some more functions to fetch all this data whenever you need it. For ex
function getName($user_id){
if(Memcache::get($user_id."_name"){
return Memcache::get($user_id."_name");
} else {
//Call another function which will fetch the data from the DB and store it in the cache
}
}
You will need to create functions to fetch every kind of data related to the user. And as you said you want to update this data on some major event. You can try updating the data using CRON or something like that, because as tazer84 mentioned users may never log out.
I also use what the OP described to avoid calls to db. For example, when a user logs-in, i have a "welcome-tip" on their control panel like
Welcome, <USERS NAME HERE>
If i stored only his user_id on $_SESSION then in every pageview i would have to retrieve his information from the database just to have his name available, like SELECT user_name FROM users WHERE user_id = $_SESSION['user']['user_id'] So to avoid this, i store some of his information in $_SESSION.
Be careful! When there is a change on data, you must modify the data in db and if successfull also modify the $_SESSION.
In my example, when a user edits his name (which i also store in $_SESSION so i can use it to welcome-tip), i do something like:
If (UpdateCurrentUserData($new_data)) // this is the function that modifies the db
{
$_SESSION['user']['user_name']=$new_data['user_name']; // update session also!
}
Attention to:
session.gc_maxlifetime in your php.ini
This value says how much time the $_SESSION is protected from being erased by the garbage collector (the file that exists on your disk in which the $_SESSION data are stored)
If you set this very low, users may start getting logged-out unexpectedly if they are idle more than this amount of time because garbage collector will delete their session file too quickly
if you set this very high, you may end up with lots of unused $_SESSION files of users that have left your website a long time ago.
also i must add that gc_maxlifetime works together with session.gc_probability where in general you need lower probability for high-traffic websites and bigger probability for lower traffic since for each pageview there is a session.gc_probability that garbage collector will be activated.
A nice more detailed explanation here http://www.appnovation.com/blog/session-garbage-collection-php
I know this sounds stupid but ....
If ur data is not sensitive the best way to make it accessible faster is to store it in hidden variables inside the forms itself. You can save comma separated or values in an array.
Ok, i have one totaly noob question about php sessions:
I have 3 (and more) php pages, i need to protect them with login system and sessions. Now, i am including this to the top of every page:
session_name('somename');
session_start();
if(!$_SESSION['user_loggedIn']){
header("location: login.php");
}
if (isset($_SESSION["timeout"])) {
$inactive = 900;
$sessionTTL = time() - $_SESSION["timeout"];
if ($sessionTTL > $inactive) {
session_destroy();
header("location: login.php");
}
}
Question: is it correct to add something like include session.php; to top of every php file, ofc. session.php would include only code above.
You shouldn't need to handle the session timeout yourself, your webserver is almost certainly handling that for you already. All you should need to do is check to see if the session exists and make sure you have login info in that session.
Also, as far as "what's the right thing to do" -- if you require it at the top of every php file, remember to use "require_once" because there's no point in doing the same thing over and over if you include other files. Also, you may only need to do this on pages where you know you only want secured users, which isn't always every page of the site.
PHP is a programming language that is similar to JavaScript but allows for better functionality of the code to develop dynamic websites and apps. PHP stands for Hypertext Pre-Processor. In this tutorial, I will walk you through what a session is, how to declare session variables, and introduce you to a few functions that will allow you to get your session up and running in the way you need it to.
What Is a Session?
First, you may be asking yoursslef, “what is a session?” In this programming language, a session is “used to store and pass information from one page to another temporarily (until the user closes the website).” If you are familiar with cookies, sessions are a very similar topic. While cookies are only stored on the local computer and browser that you use, sessions get stored on your machine as well as on the server you’re using. Both of these collect information about the way you interact with the webpage to improve the experience for a user. To summarize the two of them, “data that is kept in cookies is solely kept on the client’s side, whereas the information kept in sessions is kept on both the client and server’s sides.” (The link to the article I found this can be found here).
The most common functions that you will use as you begin to learn PHP are the session_start() function, the die() function, and the session_destroy() function. These three functions allow you as the user to start specific tasks and then stop them whenever you want. The session start function will allow you to, of course, start a new session. The die() function will allow you to clear any session variables that you may have used during your session, and the session_destroy() function will end your session. Now, understanding what a session is, let’s discuss what a session variable is and how you can declare them.
What Are Session Variables?
Session variables make it possible to make sessions in PHP useful and functional. Which variables you use will be different depending on the project you’re working on, but in my project and database I used variables that helped me see the status of users on my database. I’ll share two examples (see screenshot below, lines 54-55). The two variables I declared here were “logged_in” and “username”. All session variables are declared with a unique syntax. The proper way to declare a session variable is as follows:
$_SESSION[“nameofvariable”] = “variable declaration”;
It is important that you declare your session variables in this syntax or you will not be able to have your sessions run properly. As a system administrator, these variables help me to see who is logged into the databases and making edits to tasks. In addition, the logged_in variable enables functionality of the database and webpage. If the user is not logged in, then the code knows to redirect the user to the login page. See the example below:
Screenshot 1:
I then used these variables to help me keep track of the state that my program and database were in to allow it to function properly.
Let’s Get To It: How to Set Up Your Sessions
Now that we understand more about what a session is and how session variables can help us accomplish our goal of a functioning program, let’s discuss the process as to how we can actually implement this. First off, go ahead and open up your IDE. I personally picked Visual Studio Code as it allows me to comfortably program with color codes, but you can pick whichever one you choose. In this example I will show you how I set up both of my sessions using a particular action that implemented my to-do list to my database. Although the code I will share will be specific to my project, the principles will remain the same for all PHP code.
In the screenshot at the end of this section I have some code I wrote at the top of an action file that ultimately ended up allowing a registered user on my webpage to sign into their to-do list. Because this was an element that required the database to be fully implemented, I knew that I had to use the PHP language. In this screenshot and in your code, you should start your code with the simple PHP starter code of:
<?php
That’s right! That is all you have to do. This allows your IDE to recognize what you will be coding in. Once it has this information you get to set up your session which, believe it or not is another easy step. In order to declare that you’re going to be starting your session all you need to do is declare the following code:
session_start();
In order to properly run your sessions, it is vital to know and understand that this HAS to be the first thing declared in your code document otherwise it will not function properly. Once this code has been declared then the computer knows to iterate through the code in your document until another function is called telling it to stop. Once your function is declared you have the chance to declare your session variables and any other information you need the computer to know. Here in screenshot 2 I have the visual example of me declaring my php language, starting my session, and declaring the variables that are unique to me that establish my connection from my to-do list to my database. This is my 2nd screenshot:
Screenshot 2:
From this example you can see from lines 1-16 of my action file. Everything that I did here is what was explained in this section.
Useful Tip:
Another function that allows you to properly manage your session is the die() function. I implemented this one in my file. It is a way for the script to be stopped while keeping your session open. This was useful to me because it was a way of letting my script know to stop and moving to the next portion of my instructions, which were found in another file. If you are coding a particular project that requires multiple actions, then this is a great function to keep in mind!
Destroying (Ending) a Session
The word “destroy” sounds pretty hardcore, but in PHP sessions destroy is just a word that means “end”. The syntax of this function within the session is the following:
session_destroy()
The destroy function will take any and all data that you used during your session and destroy it. However, it is important to note that it will NOT reset or delete any of the global variables that you may have declared during your coding. In order to start a session again you need to code your project to have the first function, start_session(), called again.
End Result
You may or may not be coding a database, but the steps that I listed above should be a place to allow you to learn the basic principles of what a session is, how to start one, declare variables, and end your session at the appropriate time. In my particular database project I was able to use sessions to allow users to login to a page, log out of their account, register a new user, to update actions included in the database, and more. Whatever your project may be, sessions have a great ability to adapt to the needs that you have as a coder. In the extremely rare event this tutorial didn’t answer every question that you have, I have also included a list of some additional links and videos that may help you answer any unanswered questions about sessions in the PHP language. Happy coding!
Additional Resources:
https://www.javatpoint.com/php-session
This website is a great resource for studying more about what a PHP session is and all basic information about what they do. This page also includes information on specific types of sessions, how to code them, how to implement them, and when they should be used.
https://www.tutorialspoint.com/What-is-the-difference-between-session-and-cookies
This is a great resource for understanding the differences between sessions and cookies, and for also seeing how they are similar. This website is comprehensive in how it compares the two features, even going into detail on their capacities, functions, data storage, and format.
https://code.tutsplus.com/tutorials/how-to-use-sessions-and-session-variables-in-php--cms-31839
This website does a deep dive more into what a session is and defines Session Variables for the PHP language. It goes into detail on how to start sessions and also talks about some common errors that may occur.
https://www.javatpoint.com/php-session
This link has outstanding information and further descriptions as to how to destroy, or end, a session. It also goes into further detail on what it will do to your project and code in addition to describing what it will not do.
https://www.youtube.com/watch?v=h6KID8n0zCU
This is a great video that describes sessions. I personally like to refer to it as “Sessions for Dummies”.
I´m having some serious trouble debugging this particular problem and I hope someone has a clue what i´m doing wrong.
I have a Custom CMS system working that uses Paragraphs as building blocks that get updated using Ajax(prototypejs) calls and functions that parse the HTML chunks in given order, clean them up and save this data in associative arrays in a Session variable.
Users log in, Session is created and I can check for this session without problem in every page I need it. The system works directly on the definitive websites, so the user can see his updates on realtime and browse the site as a normal user would do, but editing.
So, nothing new here. But here is the weird thing.
Enduser site on edit mode(admin user logged in): path "/"
After the logged status is verified, a function processes the editable content and saves an associative array to session, it also starts some javascript objects for editing every paragraph. Data is actually saved, I can use an external script to check if it´s there after this php script ends.If I load a new page(new content), Session gets updated with new data)
Admin User modifies a paragraph using an Inplaceeditor and this HTML chunk is send via Ajax to a php script that starts the named session, reads the present session data, checks if a paragraph should be modified, appended or deleted and reassigns values to existing array keys in $_SESSION. if i make a var_dump() o print_r to $_SESSION after assigning new data is there.After that the script echoes the processed html, and ajax updates the original paragraph on the calling page.
This script is in /admin/cms/...etc, that means at least 4 directories inside the root of the site.
When the script ends, I check using the same session dump script to see if data was really written/commited, but no, $_SESSION has only the original data from the calling page.
Same ID, same session name, same session_start() but no data gets written.
This whole operation is very quick, so I though it could be a speed problem, scripts ends before session_write_close can make his work.
But if I add a new key to $_SESSION array and put some data there, data gets updated and written. If i don´t output anything on this script and just process data and set session variables it also get´s updated and written.
It´s like some members of $_SESSION array are getting blocked to update.
What i did to track this error and what i´m sure i´m not doing wrong.
1.- register_globals are off of course
2.- session_name() and session_start() are always present and in the given
order. I used to have multiple
session_start() -close on a same page
to use several named sessions, but to
refine the problem this is not longer
so.
3.- I use session_write_close() after session data is processed. Also
tried without, letting php decide
when to commit data, but no luck.
4.- I`m using only cookies for SID.
5.- sessions are stored on /tmp, i can see the data getting updated.
I also tried using a custom save
handler on DB, but same problem,
"_write" got only called when no output as present.
I searched php.net, stackoverflow, google, etc for this subject. I never ask without investigation, this is my first time in many years...but it´s just so unlogical it must be something tiny a haven´t thought of.
The most weird thing is that when I just process data without output $_SESSION gets updated ok. But if i modify this script afterwards by adding the output and try again, instead of just having the new(last) value present I get the original value back, the one created by the calling page at first place, sometimes after playing around a few times! PHP can´t cache values between scripts or?I dont have globlals on.
I´m really clueless. This system worked flawless on PHP4.3, since i´m using 5.3.3 for two moths my users where caliming data where getting mixed up, so i checked and yes, there are serious problems. Today I updated to (5.3.6) and I can´t get this session values commited.
Script code called via Ajax:
<?
session_cache_limiter('nocache');
session_name("CMS_ses");
session_start();
include('../htmLawed/htmLawed.php');
include("utils_cms.php");
include("../../../php/utils_array.php");
$value=$_POST['value'];
$editorId=$_POST['editorId'];
$clase=$_POST['clase'];
$editorId=str_replace("pre","",$editorId);
$value=html_entity_decode(stripslashes($value),ENT_QUOTES);
if (strlen(trim($value))==0)
{
die();
}
$value="<div id=\"$editorId\" class=\"$clase\">$value</div>";
$newXHTML=$value;
$retorno=CMS_nuevoBloque($newXHTML,$editorId);
$_SESSION['data']['CMSeditores']=$retorno[1];
$_SESSION['data']['CMScont']=$retorno[2];
session_write_close();
print_r($retorno[0]); //Offending part...without everything works
?>
really nothing strange here....main page code is even simpler, no strange php directives, etc.
Here is the header of the caller page
include 'php/db.php';
$len=$_GET['len'];
$sec=$_GET['sec'];
$cont=$_GET['cont'];
$admfin=$_GET['admfin'];
$fecha=$_GET['fecha'];
$token=$_GET['token'];
$cur=$_GET['cur'];
$PHP_SELF=$_SERVER['PHP_SELF'];
session_cache_limiter('nocache');
session_name("CMS_ses");
session_start();
$passvar='';
unset($adm);
if ((!empty($_SESSION['cms_logged'])) and (!isset($admfin)) )
{
$nivelpermisos=$_SESSION['cms_logged_group'];
$useractual=$_SESSION['cms_logged'];
$adm=1;
}
elseif (empty($_SESSION['cms_logged']))
{
unset($useractual);
}
//.........rest of the code
UPDATE: I did late night tests and found someting i don´t understand.HElP please:
It has not only to do with Sessions but also with Mysql Querys. Same code, but instead of trying to write to $_SESSION array i made a simple update to a Innodb table using the session_id. When i Output some code, the update does get executed,(i can output the query string and no mysql_error() or notice) problems, but checking the database the row doesn´t get updated. Letting the output out if the script and Query does get commited. Only common thing is sessions are started and output is made.
I restarted Apache, etc(who knows) but no luck. Then i made something really stupid, because this is a server side thing. I changed my browser to Firefox(using safari) and everything works! Ok, recheck, back to safari, nothing works. Both running side by side, same issue. PHP is server side, how can different browsers handle code different, can a browser say to apache rollback, request not handled or call the same script twice without notice(checked safaris developer console and the script is called only once) ? Can safari resubmit data silently because it "thinks" ajax failed? I checked headers using firebug and Safaris developer tools , nothing strange but whenever i make a Ajax call with safari, the caller page reloads data(Aka conection to server...).
I really don´t understand nothing.
I had a similar problem to this (if I have understood correctly). I needed to force session data to be written (for a custom session driver) after scripts have finished running. A shutdown function can be registered which should run after scripts have finished.
Maybe this will solve (or help you to solve) your problem.
http://php.net/manual/en/function.register-shutdown-function.php
Thank's for your help. I was doing everything in the right order and still session data was not being written. Session names where necesary because sometimes we test many sites on the same domain using the same custom CMS. So, finally, after making lots of test and no luck, i found that register globals was active on this server(we never use it, code was written having this option off in mind of course), but it messes with sessions!. Switching this off made a huge change. No more problemas. I also made a custom session handler in DB, so i could track the problems in an more centralized way.
Conclussion: Never use register globals + named sessions, an complex data in sessions.
Anyway, i will give this issue more time and more tests. Ajax calls are also sometimes too fast, i had to put a sleep command so writing the session data was really done.Thanks
I am not sure but few suggestion i think may be helpful.
delete session cookies before refreshing the page for testing purposes :)
Ensure that you're not assigning any arrays with a key containing the pipe character (|). This will prevent the session data from being serialized and saved.
Do session_regenerate_id(true); many cases session_write_close doesn't seem to matter with out session_regenerate_id. or just do session_start() after session_write_close() if you are relying on SID ; and in your case i think this is what is causing problem to you as you are ending the current session every time and not re starting it for the next page. hope u get my point. Further more To Make sure data is actually flushed out to the browser use ob_end_flush();
i could not understand the connection between
$_SESSION['data']['CMSeditores']=$retorno[1];
$_SESSION['data']['CMScont']=$retorno[2];
and
$nivelpermisos=$_SESSION['cms_logged_group'];
$useractual=$_SESSION['cms_logged'];
i think you need to paste some more code where the data part is causing problem instead of admin login part.
i hope this helps you.:)
Is there any reason you're establishing the session name twice? I've had issues in the past where I would establish the session without a name, then another piece of script (not mine) was naming the session. Even at the end of the script I was able to print out the session variable, but once I went to a new page my session had been forgotten. It wasn't until I copied the name included in the 2nd script into my session call that it was solved.
Check that there's no other session names being used; also, maybe try only naming the session once, at the first call to the session?
Question: Are you calling session_start() first thing... before ANY output to the browser and before any variables are assigned?
Sounds silly but give it a try.
Also, why are you using session names? Really not necessary unless you have a lot of session variables with the same name serving different purposes and if thats the case then you need to fix that first!
I had a similar problem but it was having with ie few years back. IE manipulates the header on its own way and that causes strange php bugs that you can find in php.net archives.
#Diego Pino Navarro, please see this help page and find Safari and it's issues with php.
I also found "Safari "forget" http-authentication's logon-information".
I'm using a SESSION variable to set the pre-allocated record id from Postgres (getting the record id sequence) using PEAR's DB nextId(). I set the I id to a session variable because of scoping issues in the legacy code I'm working with. After the INSERT happens I use the unset() to remove the SESSION variable (This is to clear the used record id). There is more information in the session as well that remains intact, it's just the next_id element that is being removed.
Pseudo code:
// Get the next Id and set to SESSION
$_SESSION['next_id'] = $db->nextId();
... more code here
// After insert
unset($_SESSION['next_id']);
My question is, Would clicking the back button on the browser somehow reset the SESSION variable $_SESSION['next_id']? Maybe causing it to be NULL? How does CACHE handle the SESSION after an element has been removed but the user has returned to a previous state?
EDIT:
the reason for the question is that the code in production is randomly (by any user) trying to INSERT with a NULL record id (Which is the next_id from SESSION). Just trying to debug the process as the code is very minimal, reviewed by my peers and has just stumped us???
EDIT 2:
Wow I guess there is an issue with how I'm using the SESSION variable.
Well I'll explain as much as I can as to why I chose this method.
First the code is in the process on being rewritten from PHP 4, but the current production version is mostly PHP 4 with a ton a newly added module code in PHP 5.
The reason I chose the SESSION variable is because of a scoping issue that would need to be hard coded on several hundred pages of legacy code or on one page and cast the value into the SESSION which all pages have access to. (well my boss who pays my salary like the option I chose).
The original problem is they (my boss) wanted to display the id to the end user before the insertion of the information. Hence the PEAR DB call nextId(). We use PostgreSQL and I'm using the record id sequence to ensure that the next id will be unique and allocated to the end user only (No duplicates as Postgres handles locking this in the sequence).
So the end user can also navigate to multiple pages during the process, this also is another scoping issue.
Now using the SESSION and retrieving the next Id with some validation and checks is about 50 lines of code for the whole process instead of the thousands of lines of code that would have been written to do this the correct way.
Again NOT MY CODE in the first place, just making the best solution at the least possible cost.
If you have another, better, greater, easier, cheaper solution feel free to post away. But if you're going to piss on my decision about how to code, then please pay my bills and I will fully agree with following better coding standard,practices,solution.
Can't imagine a scenario where you would need to store nextId() in session to be used on a next page.
As webbiedave pointed out - $_SESSION is stored on a server, so no - hitting back button will not "reset" the session variable.
But, if user hits refresh on a second page (the one that cleared the _SESSION variable) your script will be launched again, with next_id set to null (because it is set to nextId() on a previous page)
The same will happen if a user hits the back button and the previous page will be loaded from browser cache - no request to a server, no next_id variable in a _SESSION.
But still, there is something really wrong if you store nextId() in a _SESSION.
Just bypass the insert all together if $_SESSION['next_id'] comes up NULL, even if it means calling die() before you reach that legacy code you don't want to touch.
Are you sure the session itself isn't being flushed on the server-side? I had a situation in a shared-hosting environment where the server settings were caused my sessions to disappear. I had to add local settings in my app to overcome this (private rather than common session storage).
These are the settings I have in my .htaccess file for the sessions, giving them reasonable time on the disk
php_value session.gc_probability 1
php_value session.gc_divisor 100
php_value session.gc_maxlifetime 3600
Found the cause of the issue. End users are opening multiple tabs in their browsers causing the SESSION data to span to any open tab as they all would call the same session. So submitting one request in one tab, unsets the session in all tabs. So when they submit the request in the second tab the session is missing the next_id value causing all the problems. User training will solve the issue for now but looking to implement things in a new way soon.
Thanks for all the efforts
This may be a bit of daft question, but I don't come from an OOP background and although I'm reading and learning as I go I'm still struggling with a few concepts.
Right now I'm working with PHP 5.3 and desiging a fairly simple login using a few different object classes: User which defines the user. Session which starts and maintains session data and if someone is logged in, and Database which does the queries.
So when my script is run, my session object is instantiated, etc... here's my problem though. When I move from one page to the next how is that object tracked? Or perhaps rather my question is how does PHP know the objects that relate to my login are mine and not someone else who logged into the site?
I know if I'm doing this in a non OOP way, I'd simply check the session cookie on each page and check my data that way, which is fine my brain can handle that. But, where and how is object data tracked.
EG:
On each page I want to check if someone is logged in I reference $session->is_logged_in() etc is_logged_in checks the a private variable name is true or false.
There's no checking of cookies at this point which means this object still exists, and, as it keeps asking for a stored variable the instance must persist to be useful... but how does PHP, the server, whatever tie that instance of that object to that user? If all of these objects float around on the server till I destroy them won't there be lots of memory used by objects?
As I said at the start it's probably a really basic, fundatmental question but I'm yet to have my eureka moment with this, I might go back to simpler PHP.
Session data (that is all the data in $_SESSION) is by default serialized and stored to file between requests. The data gets unserialized automatically when session_start() is called.
From the PHP manual on Session Handling (emphasis mine):
The session support allows you to register arbitrary numbers of variables to be preserved across requests. When a visitor accesses your site, PHP will check automatically (if session.auto_start is set to 1) or on your request (explicitly through session_start() or implicitly through session_register()) whether a specific session id has been sent with the request. If this is the case, the prior saved environment is recreated.
Nothing is persisted in memory between requests. PHP has a shared nothing architecture, meaning all objects are recreated on each request anew, unless you are using dedicated cache mechanisms.
So when my script is run, my session object is instantiated, etc... here's my problem
though. When I move from one page to the next how is that object tracked? Or perhaps rather
my question is how does PHP know the objects that relate to my login are mine and not
someone else who logged into the site?
When you start a session, an id is generated. All the session data is associated with that id and it is given to the browser to store in a cookie. Subsequent requests include that id in the cookie, and PHP pulls the data out from where it has stored it.
If all of these objects float around on the server till I destroy them won't there be lots of memory used by objects?
The objects are serialized to files rather than being held in RAM, and are cleaned up with the session expires.
I find that sometimes, when I start to lose perspective as to whats really "happening", a quick trip to a page with phpinfo();,or just logging some ENV variables often clears things up, and puts me back on track…
Globals let you see exactly what "exists" in your environment, and allow you to take a mental restocking of what you're "working with", and how to best attack the challenge.. You'll find a wealth of information, and as to your specific "issues" there are such entries as…
$_SERVER["HTTP_COOKIE"]
$_SERVER["QUERY_STRING"]
$_SERVER["argv | c"]
$include_path
etc…
also, it never hurts to read through your /etc/php.ini (wherever the case may be) for a little one-on-one-time with PHP's internals - to remind you "what its all about".