PHP Session Not Restoring from Cookies - php

When a user returns to my website, it attempts to restore their last session from the $_COOKIE associative array. It's not working as expected. I can look in my browser's cookie manager and see that the cookies are there, but they don't seem to be getting saved to the $_SESSION associative array.
This is essentially the program flow when a user returns to my site:
foreach ( $_COOKIE as $name => $val )
{
$_SESSION[$name] = $val;
}
session_start();
...
$some_var = $_SESSION[$var_name];
Do I have things out of order, or should I not be overwriting PHPSESSID? Any insight as to what I'm doing wrong would be appreciated. Thanks.

You're getting sessions and cookies mixed up. You don't need to put things into the $_COOKIE array. Just use session_start() and then put things into $_SESSION. PHP will automatically then manage the session/cookie for you.
$_COOKIE variables are stored on the users browser, so they aren't secure and can be manipulated by the user => security risk.
$_SESSION variables are stored only on the server. The only thing stored in the cookie is a session_id, so $_SESSION variable can't be manipulated.
Does that make sense?

Put session_start() before anything else; this function initializes the session data that you will be accessing in $_SESSION.
Not exactly sure what you're trying to achieve with the rest of it all, but session_start() first is a starting point...

Related

Session superglobal array

I just noticed that session_destroy() does not seem to be working for me.
Testing PHP code looks like this:
session_start();
session_destroy();
$_SESSION['session'] = 'session started';
print_r($_SESSION);
But the display still shows
Array ( [session] => session started)
Surely this should throw an error as the SESSION variable now does not exist?
session_destroy destroys the saved session data - in most cases, that's the session file.
However, it doesn't affect the session variable itself.
Therefore, so long as you are in the same request, you can continue to use the $_SESSION superglobal with all its previous values. To completely destroy that, you should use:
foreach(array_keys($_SESSION) as $k) unset($_SESSION[$k]);
Or code to similar effect.
That said, it doesn't matter much - the session will be destroyed, and usually you only do this on logout pages that will only be displayed briefly before sending the user back to the homepage.

How to completely destroy session variables on logout

When I log a user out of an app I am building I use session_destroy();
But when I go back to the page, all session variables are still set.
How can I completely destroy all session variables and ultimately require a user to log back in again?
Here is my code:
session_unset(); // clears all session variables
$_SESSION = array();
session_destroy(); // deletes session id
Thanks
After using session_destroy(), the session cookie is removed and the session is no longer stored on the server. The values in $_SESSION may still be available, but they will not be on the next page load.
If you need to clear the values of $_SESSION, set the array equal to an empty array:
Of course, you can't access the values of $_SESSION on another page once you call session_destroy, so it doesn't matter that much.Still if you are concerned .
Try the following:
session_destroy();
$_SESSION = array(); // Clears the $_SESSION variable
you are not calling session_destroy() for sure, your code may be unable to access it.
Post more code so we could help you

Best way to store form values in PHP Cookie?

After a form submission I would like to store several specified form values in a PHP cookie. I need the data to persist after the browser is closed so I don't want to use sessions. My current call looks like this:
if ($_GET) {
$params = $_GET;
}
Is there a way to set several params from $_GET to a $_COOKIE so I can use them later when the user returns?
You can still use sessions for you problem. Just change the cookie parameters with session_set_cookie_params() (see here) to a time > 0 (0 implies that it should be deleted when the browser is closed) and increase the session cache lifetime with session_cache_expire() (see here).
This has the advantage that even data that the client shouldn't be able to change cannot be changed by simply changing the cookie on his machine.
Cookies only
The other approach could include some serialization (e.g. use serialize() and deserialize() or do something on your own for things of low complexity like simply joining some arguments with a delimiter) of your parameters directly stored into a cookie with the setcookie() function. Get more info about that here. With that you can read out the cookies values directly from the superglobal $_COOKIE.
Check the PHP documentation for setcookie: http://php.net/setcookie
You can use serialize(), or do a foreach() loop of all $_GET values, and set those in the cookies (different cookie for each value)
you can use foreach to traverse through GET array and set the cookies with their index names.
try this -
$expire=time()+60*60*24*30;
foreach($_GET as $k=>$v){
setcookie($k,$v,$expire);
}
This will set cookie names same as GET array indexes and will be expired after a month.

How to prevent a started PHP session from writing?

I have a situation where I've started a session with:
session_id( $consistent_session_name_for_user );
session_start();
$_SESSION['key'] = $value;
but then later I decide I don't actually want to "commit" (write) this session. PHP doesn't seem to have any kind of session_abort_write() function. I don't want to destroy the session variables from prior script runs, so I can't use session_destroy()
I tried session_id(""), but that call fails. I could "redirect" the session so it writes to another session, like session_id("trash"), but that would cause a lot of PHP (Apache) connections to try to write to the same session "file", which I want to avoid.
I'm highly simplifying the problem here, we're actually storing sessions in Memcached and this is a complex codebase. So I don't want to be sending unnecessary "trash" sessions to the Memcached server all the time.
From PHP.net,
session_regenerate_id
will replace the current session id with a new one, and keep the
current session information.
session_unset will free all registered variables
session_unregister ( string $name ) will unregister a specific variable
I haven't actually determined if this method prevents writing the session to the session store, but here's the solution I finally used:
session_id( 'trash' ); // or call session_regenerate_id() as someone else suggested
$_SESSION = array(); // clear the session variables for 'trash'.
I'm hoping this has the effect that nothing will get written, but I'm guessing it still will write a blank file, because PHP can't know that sess_trash isn't already there.
If you want to completely avoid writing the session, you'll have to use a custom session handler in PHP and set a global flag to prevent writing the session.
You could probably use something with session_set_save_handler to put dummy functions in for session handling.
<?php
function fakeIt() {
return true;
}
session_set_save_handler("fakeIt", "fakeIt", "fakeIt", "fakeIt", "fakeIt", "fakeIt");
There is session_write_close(). It dumps out the session array to storage and then "closes" it - $_SESSION will still be available and read/writeable, but any changes will no longer be saved, unless you do a session_start() again later on within the script.

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