Do I have to destroy SESSION when user logs out? - php

I only store logged users id in SESSION.
When a user logs out, SESSION becomes useless for me. Do I have to destroy it?
These are the methods of Utils class which I am using to start and destroy SESSION.
static function sessionSecureStart()
{
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
}
static function sessionSecureDestroy()
{
//Utils::sessionSecureStart(); This part is for testing only
if (session_status() == PHP_SESSION_ACTIVE) {
$_SESSION = [];
session_destroy();
}
}
Sometimes randomly I get errors/warnings like SESSION could not be destroyed.... Am I doing something wrong?
(I am using PHP/5.5.25)

You don't have to destroy the whole session, just unset the parts you don't need. Let's say that when a user logs in that you set $_SESSION['user_id'] and everything that says I am logged in is looking for that variable. A simple unset($_SESSION['user_id']); and suddenly the user is logged out. Remember, your user doesn't have control over what's in the session.
Another option is to set the session cookies to very low lifetimes. It's cruder but just as effective.

I highly advice you to destroy the session. For both security and performance.
Normally session data is saved in temporary files on the server and in a cookie on the browser, this one only contains the session id but no data.
When you call session destroy you delete this file but you also might tel the browser to delete the session cookie (sending a cookie with the same name which expires in the past). You can know the name calling the session_name() function (normally it's PHPSESSID).

When a user logs out, SESSION becomes useless for me. Do I have to destroy it?
Yes. Besides destroying it, it's also helpful to generate a new session-id
Sometimes randomly I get errors/warnings like SESSION could not be destroyed.... Am I doing something wrong?
You cannot destroy a session that haven't been started. Make sure you have successfully initiated your sessions with session_start(); before trying to destroy it

Related

How to determine cookie validity?

I am starting the session as
session_start(); //So This session will get destroyed when user exit the browser
I set the cookie as
setcookie('cookie',$value,time()+3*60);
$_SESSION['cookie'] = true; //When user log in, I don't need to get the
salt again from db and do all the security
checks. Assume it as a cache
This suggesion is suggested in this question.
The problem is, cookie gets expired after 3 minutes. But session exists. So user tries to login after 3 minutes
if($_SESSION['cookie'])
{
//success
}
else
{
//Authenticate user
}
But this is wrong. Since cookie expired, else part should execute. But if part gets executed. I understand that session is still alive. How do I handle this situation?
I understand that it is due to that time()+3*60. But how do I implement that cache thing?
You need check cookie not in $_SESSION.
Check them in $_COOKIE.
As example:
if($_COOKIE['cookie'])
{
//success
}
else
{
//Authenticate user
}
Cookies and session variables are not related (except that PHP internally uses a cookie named PHPSESSID to connect the client to its session). Expiring the cookie doesn't have any effect on a session variable with the same name. If you want to test whether the cookie has expired, use:
if (isset($_COOKIE['cookie']))

After payment success session destroying automatically

I am doing a small project in that i have user data in session. In the middle the user will do payment, after payment success, the session is destroying automatically.
Now am not able to get user data from session. (How can i achieve this with out using COOKIES).
Note: I have tried using:
header('Access-Control-Allow-Origin: *');
But no use.
Hello this is an example from PHP manual i hope it might help. Firstly start your session by session_start(); and once all your transactions are completed destroy is by session_destroy();
<?php
// Initialize the session.
// If you are using session_name("something"), don't forget it now!
session_start();
// Unset all of the session variables.
$_SESSION = array();
// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
// Finally, destroy the session.
session_destroy();
?>
$_SESSION is a special array used to store information across the page requests a user makes during his visit to your website or web application.
While there may be many users accessing the site at the same time, each with his own session, it’s thanks to unique IDs assigned and managed by PHP for each session that allows each user’s session to be available only to himself. Session information is stored on the server rather than the user’s computer (as cookie data is stored), which makes sessions more secure than traditional cookies for passing information between page requests.
Using Sessions
Before you can to store information in a session, you have to start PHP’s session handling. This is done at the beginning of your PHP code, and must be done before any text, HTML, or JavaScript is sent to the browser. To start the session, you call the session_start() function in your first file:
<?php
// start the session
session_start();
// store session data
$_SESSION["username"] = "Qateel";
session_start() starts the session between the user and the server, and allows values stored in $_SESSION to be accessible in other scripts later on.
In your second file, you call session_start() again which this time continues the session, and you can then retrieve values from $_SESSION.
<?php
// continue the session
session_start();
// retrieve session data
echo "Username = " . $_SESSION["username"];
Ending a Session
As important as it is to begin a session, so it is to end one. Even though a session is only a temporary way to store data, it is very important to clean up after yourself to ensure maximum security when dealing with potentially sensitive information. It is also good practice and will avoid having a huge amount of stale session data sitting on the server.
To delete a single session value, you use the unset() function:
<?php
session_start();
// delete the username value
unset($_SESSION["username"]);
To unset all of the session’s values, you can use the session_unset() function:
<?php
session_start();
// delete all session values
session_unset();
Both examples only affect data stored in the session, not the session itself. You can still store other values to $_SESSION after calling them if you so choose. If you wish to completely stop using the session, for example a user logs out, you use the session_destroy() function.
<?php
session_start();
// terminate the session
session_destroy();
Few Tips
Despite there simplicity, there are still ways using sessions can go wrong.
Timing-out sessions is a very important action if you are dealing with users logged in to your website or application.
if (isset($_SESSION["timeout"])) {
// calculate the session's "time to live"
$sessionTTL = time() - $_SESSION["timeout"];
if ($sessionTTL > $inactive) {
session_destroy();
header("Location: /logout.php");
}
}
Use a database to store data at the earliest moment you know the data will be persistent; don’t let it stay as part of the session for too long as this opens it up to possible attack.
Use session_destory() once you don’t need to use the session any more.
You may want to go through:
php sessions at #SO
php sessions security at #SO

Use of session_destroy() instead of unset($_SESSION['userName']) not working

I have used session_destroy in MVC pattern.
If I click logout link, it will redirect correct url but page disappears. It is displaying the below error in Firefox.
The page isn't redirecting properly
Firefox has detected that the server is redirecting the request for this address in
a way that will never complete.
This problem can sometimes be caused by disabling or refusing to accept cookies."
This is the function I'm using for logout.
Logout function:(Not working)
public function Logout(){
session_destroy();
$this->redirect('index.php?r=admin/login');
}
I have unset($_SESSION['userName']) the session variable. It is working fine. But session_destroy is not working in that place.
What is the reason for that?
Logout function:(working)
public function Logout(){
unset($_SESSION['userName']);
$this->redirect('index.php?r=admin/login');
}
you can use another way to remove session like:-
$_SESSION = array(); // define it with empty array and clear the session values
or use start the session again and then destroy
session_start();
session_destroy();
For more :- why session_destroy() not working
and for better understanding you can read #Chen Asraf answer
From the PHP documentation of session_destroy:
session_destroy() destroys all of the data associated with the current session. It does not unset any of the global variables associated with the session, or unset the session cookie. To use the session variables again, session_start() has to be called.
In order to kill the session altogether, like to log the user out, the session id must also be unset. If a cookie is used to propagate the session id (default behavior), then the session cookie must be deleted. setcookie() may be used for that.
So in order to truly get rid of the session, you also have to unset or override the $_SESSION superglobal, like you did before.

How to (if possible) set and unset session variables/ stop session cookie overwriting?

For background, here's my scenario:
I'm building a self-hosted platform for a particular niche, and part of that platform is the login process, which if validated sets a session for the user. On every administration page load, the session is started and the variable $_SESSION['key'] checked to see if it's true.
If it's false, the user is re-directed to the login page with an error telling them to login again.
The problem is this is dependant on a session cookie being set or not set, in the sense that when the session cookie expires and the session is started with session_start() to check $_SESSION['key'], therefore creating a new session cookie with default values (I use session_set_cookie_params() to alter the path, timeout etc) making it impossible to re-login as session cookies do not overwrite from what I can see.
In order to fix this I've thought about using something like session_set_cookie_params(5, ..) before session_start() when checking $_SESSION['key'], which will create a 5 second session cookie, therefore allowing a new one to be created when re-logging in, but I'm not sure whether this would work - and I'm also sure there must be a more efficient way to set/unset a session variable?
Here's my code:
Start session if validated login
if($validated){
session_set_cookie_params(1800, "/inst", $server_name['home']);
session_name("_inst");
session_start();
$_SESSION['key'] = true;
}
Check if $_SESSION['key'] is still true
session_name("_inst");
session_start();
if(!$_SESSION['key']) {
header('Location: ' . $server['home'] . '/login/?error=1');
}
Any answers or advice would be great, and please do ask if you need clarification on anything!
Just issue a session_start() on all pages. This'll unconditionally create a session for you, then you can check for the presence/abscence of the key:
<?php
session_start();
if (!isset($_SESSSION['key'])) { // never logged in, or were logged in and got logged out
... redirect to login ...
exit();
}
if ($_SESSION['key'] != 'expected value') { // logged in, but no longer a valid login.
... redirect to login ...
exit();
}
You shouldn't have to mess with the session cookie settings at all. Leave them at default and simply check for the relevant key(s). if they're not there, then the user is not logged in and should be redirected.
If their session had expired and PHP cleaned up the session file, then they've been effectively logged out, even though they have a it-was-valid-at-one-point-in-time session key, and should get redirected to login again.

Unset a specific session using session id

I am the administrator of the site. I want unset a particular session, and I know its session id.
The users are just starting the session like this:
session_id("usernumber");
session_start();
Let’s say user A has usernumber "123".
I want to destroy all the values of the user A. User A will not regenerate the sessio_id() after setting that as session_id("123");.
How can I unset destroy only for user A?
Answer by Jack Luo on php.net
$session_id_to_destroy = 'nill2if998vhplq9f3pj08vjb1';
// 1. commit session if it's started.
if (session_id()) {
session_commit();
}
// 2. store current session id
session_start();
$current_session_id = session_id();
session_commit();
// 3. hijack then destroy session specified.
session_id($session_id_to_destroy);
session_start();
session_destroy();
session_commit();
// 4. restore current session id. If don't restore it, your current session will refer to the session you just destroyed!
session_id($current_session_id);
session_start();
session_commit();
Without reverse enginering the session handler....
<?php
session_id($_GET['killsid']);
session_start();
session_destroy() || die "failed to kill";
You could try to get session_save_path() (in this directory session files are stored).
When you are using default session names the filename looks like sess_jgimlf5edugvdtlaisumq0ham5 where jgimlf5edugvdtlaisumq0ham5 is user session id so you can just unlink this file unless you dont have permissions to edit those files.
As far as I know, the only supported way to do so with the default session handler is to impersonate the user with session_id("usernumber"); and then remove the values.
You could also store sessions in a database, which would make this all pretty straightforward, yet you need to write your own session handling code.
BTW, the session ID is supposed to be a long random string which you cannot guess. Using 123 means that any anonymous visitor can easily log in with any user credentials.

Categories