PHP: Over-writing session variables - php

Question related to PHP memory-handling from someone not yet very experienced in PHP:
If I set a PHP session variable of a particular name, and then set a session variable of the exact same name elsewhere (during the same session), is the original variable over-written, or does junk accumulate in the session?
In other words, should I be destroying a previous session variable before creating a new one of the same name?
Thank you.

$_SESSION works just like any other array, so if you use the same key each time, the value is overwritten.

Tom,
It depends on how you use the session variable, but it generally means "erasing" that variable (replacing the old value by the new value, to be exact).
A session variable can store a string, a number or even an object.
<?php
# file1.php
session_start();
$_SESSION['favcolor'] = 'green';
$_SESSION['favfood'] = array('sushi', 'sashimi');
?>
After this, the $_SESSION['favcolor'] variable and the $_SESSION['favfood'] variable is stored on the server side (as a file by default). If the same user visit another page, the page can get the data out from, or write to the same storage, thus giving the user an illusion that the server "remembers" him/her.
<?php
# file2.php
session_start();
echo $_SESSION['favcolor'], '<br />';
foreach ($_SESSION['favfood'] as $value) {
echo $value, '<br />';
}
?>
Of course, you may modify the $_SESSION variable in the way you want: you may unset() any variable, append the array in the example by $_SESSION['favfood'][] = 'hamburger'; and so on. It will all be stored to the session file (a file by default, but could be a database). But please beware that the $_SESSION variable acts magically only after a call to session_start(). That means in general, if you use sessions, you have to call session_start() at the beginning of every page of your site. Otherwise, $_SESSION is just a normal variable and no magic happens :-).
Please see the PHP reference here for more information.

Related

PHP session seen as local variable

I have a problem with PHP session. When i start session, and try to add a variable to it i can only get in the same PHP script where i declared it like it's normal variable. Browser debuger also seems to not see any variable in session.
<?php
echo session_start(); //This returns 1 so session is created
$_SESSION["A"] = "B";
echo $_SESSION["A"]; // And this prints "B" as predicted
?>
But there is nothing in session!
You are confusing server-side PHP sessions, with the client-side JavaScript sessionStorage here. Both are two completely different things.
https://www.php.net/manual/en/intro.session.php
https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage
Browser debuger also seems to not see any variable in session.
PHP session data is kept on the server, the browser can never “see it”, unless you explicitly output it somewhere (as you did with echo $_SESSION["A"];, but even then it of course won’t show in the sessionStorage debug panel.)
i can only get in the same PHP script where i declared it like it's normal variable.
Then you most likely neglected to pick your session up again in the other script files. You need to call session_start at the beginning of all of them.

Using session variable to use info on different pages

i'm having a bit of a problem. I'm trying to set up a simple webpage with only three .php pages. I want a session variable $_SESSION['userID'] to be set when a user is logged in and I want the index page to show extra info if someone is logged in.
On index.php I want to show some info, if a user is logged in I want to show some extra info.
login.php - simple log in form.
login_exe.php - takes care of database connection and verification.
So this was my idea:
On index.php, check if session is started, if not: start.
<?php
if (!isset($_SESSION)) {
session_start();
echo "session started";
}
later on, check if $_SESSION['userID'] contains a value, if so: print a string
if($_SESSION['userID'] != null){
echo "User logged in";
}
On login_exe.php i've almost the same code:
<?php
if (!isset($_SESSION)) {
session_start();
echo "session started";
}
in verification function:
$_SESSION['userID'] = $data['userID'];
header("Location: index.php");
The problem is that a new session is started on every page. How can I fix this and only start the session once? Thanks in advance
You should just put session_start() on top of documents that using sessions. Say, if you have 5 .php files that using sessions, then put 5 times the session_start() on top of them.
This is because session_start() sends headers and headers must be sent before any output (for example, any echo or whitespace).
Then, you should use something like isset($_SESSION["foo"]) and not just the entire $_SESSION array, where foo is something you set previously.
If you dont want sessions at all or need to reset the entire array, just call session_destroy() which effectively destroy the current session. Use unset($_SESSION["foo"]) when you want to get rid of a key.
Finally, you might get weird cases where you cannot read session key you write at. In these cases check what is the path of sessions and if they're writeable, or change their path:
$path = session_save_path(); // what is the path
is_writable($path); // can i write to it?
session_save_path("my/new/path"); // change the darn path;
// put -even- before session_start()!
:)
glad i help
I think the PHP manuals are really good compared to ...ahm, so just read about session_start(). It says:
session_start() creates a session or resumes the current one (...)
so all you need is session_start() very early in your code. This must be executed on every request (maybe as include).
Your code checking the userId looks fine, one important hint here: you should know exactly what isset(), empty() and the like mean in PHP, so always have the comparision of comparison at hand.
You should not ask new answers (edit: questions) in comments. Be as systematic here as you are in coding.
How to end a session:
This gives room for discussion, because there is the session cookie, which is client side, and the session data, which is server side.
I recommend:
$_SESSION = null;
Reason: this will clear all login and other associated data immediately. It leaves the cookie intact, which is normally of no concern, since all associated data is gone.

Save Constant GET Variable In A Session

Can some explain to me the best way to store a $_GET variable in a session and the only way the sessions changes is when we verify the data the session is being change to is different from the GET variable.
Currently i have
$tid = clean_get($_GET['tid']);
in a global file which is included on every page the problem with that is the value of $tid will be erased and not stored in a session like i want it to once the user is not on a page with $tid set in the url.
If you get $_GET['tid'] in url then set session again by that new value otherwise restore it from session. Thats it.
session_start();
$tid = (isset($_GET['tid']) && $_GET['tid']!="") ? clean_get($_GET['tid']) : $_SESSION['tid'];
Try this and tell me is it solved?
Use a function like isset() to see if it is being sent. Only then should you replace it:
if(isset($_GET['tid']))
{
$tid = clean_get($_GET['tid'])
// Do stuff to change session data.
}
I think what you are looking for is something like
session_start();
foreach ($_GET as $key=>$value) {
$_SESSION['getValues'][$key] = clean_get($value);
}
This will store all the values in $_GET in the $_SESSION. To retrieve the values later, you just have to use $_SESSION['getValues']['tid'] after calling session_start().
Here I'm assuming that clean_get() is just something that formats and/or escapes data that came in from forms, so calling it on each value before sticking into the session will do all that cleaning when needed.
Note: only call session_start() once, and make sure you do so before doing anything with $_SESSION, otherwise you'll get error messages.

PHP create session for later PHP page

I want to save some values to the $_SESSION variable, I tried to create sessions like this:
if(isset($row_WADAsarenewals['AgreeNum'])) {
$_SESSION['AgreeNum'] = $row_WADAsarenewals['AgreeNum'];
}
But when I try to display this session like this it does not show up? echo($AgreeNum); What am I doing wrong?
To echo your session you will need to call the session-variable, not a regular variable with the same name as the the session-variable. So your echo would be:
echo $_SESSION["AgreeNum"];
Also, if you are having problems writing to your session, you might have to call session_start() prior to writing anything to your session.
You need to use
session_start()
at the beginning of your new script.
You need to use session_start(); prior to store something on the $_SESSION.
Then on the page you want to display the stored values, resume the session by calling again the session_start(); function. And retrieve the stored data like $AgreeNum = $_SESSION['AgreeNum'];
A call to echo($AgreeNum); should output the stored value.
You need to do;
echo $_SESSION['AgreeNum'];
Your solution just work when you have http://www.php.net/manual/en/security.globals.php turned on, which is not recommended. Because then $AgreeNum can came from $_GET for example.

What happens to the $_SESSION array if a PHP session times out in the middle of a request?

I have always wondered, if a PHP session times out during the middle of executing a script, will the contents of the $_SESSION array still be available until script execution ends? For example:
session_start();
if(! isset($_SESSION['name'])) {
echo 'Name is not set';
exit;
}
// imagine there is a bunch of code here and that the session times out while
// this code is being executed
echo 'Name is ', $_SESSION['name']; // will this line throw an error?
Is it practical to copy session variables to the local scope so I can read them later on in the script without having to keep checking for a session time out? Something like:
session_start();
if(isset($_SESSION['name'])) {
$name = $_SESSION['name'];
} else {
echo 'Name is not set';
exit;
}
// bunch of code here
echo 'Name is ', $name;
don't worry about such things. Nothing will happen to the session. It's initialised by sessioni_start() and $_SESSION will be always available within your script.
The default three-hour session lifetime is reset each time you open the session (see session_cache_expire), so the only way a session could time out in the middle of a request is if a request takes three hours to process. By default PHP requests time out after just 30 seconds, so there's no danger of session expiry during a request. Furthermore, the $_SESSION variable won't suddenly change in the middle of a request. It's populated when the session starts, and that's it.
The variables are copied into the $_SESSION global at the initial request, so it has the same effect as copying it to a local variable.
However, for clarity sake, it makes sense to copy it to a local variable. Especially if you plan to use the variable several times. It can be difficult to read code that has $_SESSION['variable'] all over the place.
What you needed to understand is how sessions work. A client accessing a script using a $_SESSION super global only knows the key to the session that belongs to them (Stored in Cookie/URL). This means the session data itself has nothing to do with the client. If you have the key to the session data you want to use then you can use it. Older versions of PHP had some security holes because sessions where stored somewhere that was easily accessible (I don't remember details).
Basically, if you have the session id in a PHP script you have access to that session unless the memory on the machine is flushed/harddrive is corrupt (ie Computer Restart/Device Failure).
Hope this helps, otherwise go to php.net and dive into the details on how sessions work.

Categories