setcookie is not working after uploaded to live server - php

I have used setcookie in php to check users visiting my site. The thing is when i test it in my local server it works, the cookie gets set but when i upload the page in cpanel the cookie doesn't get set.
Below is a synopsis of my code:
<?php
session_start();
//set the cookie time to desired value;
setcookie("user", "abc", time()+3600);
//some other codes
if(!isset($_COOKIE["user"]))
{
//some other codes
}
?>
Any help will be much appreciated. Thanks

Regarding the answers to my questions in the comments, you probably just need to modify the cookie lifetime of your session and not create another "user" cookie.
// TTL (Time To Live) of the cookie stored in the browser.
ini_set('session.cookie_lifetime', 432000); // 5 days
// On the server side, the garbage collector should delete
// old sessions too, after the same TTL.
ini_set('session.gc_maxlifetime', 432000); // 5 days
// Fire the garbage collector only every 100 requests.
ini_set('session.gc_probability', 1);
ini_set('session.gc_divisor', 100);
Do that at the beginning of your code, typically in a config.php file included at the bootstrap of your app.
You can see more in the PHP session configuration.
There's a little problem regarding the lifetime: the cookie will expire after the lifetime set, but since the cookie was created, so at the moment your session was initiated the first time at login.
Usually, you want the cookie lifetime to start at the last user's action. You can do that by updating the cookie so that PHP re-sends the Cookie HTTP header to overwrite it. I also added a bunch of other security settings one should do on PHP sessions. Everything is commented in the running example below:
<?php
/**
* Testing PHP cookie settings and improve security.
*/
// The cookie lifetime in seconds.
define('COOKIE_LIFETIME', 10);
// Simulate user's data from the database.
$user_mail = 'james.bond#gmail.com';
// A salt per user is good. It avoids an attacker to be able
// to calculate the session cookie name himself if he discovers that
// it is just done by hashing the user's e-mail.
$user_salt = 'nbVzr432';
// Detect if we are over HTTPS or not. Needs improvement if behind a SSL reverse-proxy.
// It's just used for the cookie secure option to make this POC work everywhere.
$is_https = isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']);
// On the PHP server side, the garbage collector should delete
// old sessions after the same lifetime value.
ini_set('session.gc_maxlifetime', COOKIE_LIFETIME);
// Fire the garbage collector only every 100 requests to save CPU.
// On some OS this is done by a cron job so it could be commented.
ini_set('session.gc_probability', 1);
ini_set('session.gc_divisor', 100);
// Improve some session settings:
ini_set('session.use_cookies ', 1);
ini_set('session.use_only_cookies ', 1);
ini_set('session.use_strict_mode ', 1);
// This POC will just print some plain text.
header('Content-Type: text/plain; charset=utf-8');
// Change the session cookie name so that an attacker cannot find it.
$session_cookie_name = 'SESS_' . sha1($user_mail . $user_salt);
// Store all the session cookie options in an array.
$session_cookie_options = [
// Set the cookie lifetime (the browser sets an expire to delete it automatically).
'lifetime' => COOKIE_LIFETIME,
// The cookie path defines under which relative URL the cookie should be sent.
// If your app is running under https://your-site.com/shop/ then the cookie path
// should be set to /shop/ instead of the default / as there's no reason to send
// your shop's session cookie to another app running at https://your-site.com/forum/.
'path' => '/',
// Cookie domain. Use null to let PHP handle that. But if you want a session
// cookie accross multiple sub-domains such as forum.your-site.com and shop.your-site.com
// then you should set the domain to ".your-site.com".
'domain' => null,
// If we are in HTTPS then don't let cookies be sent over HTTP.
// Here I used $is_https to make it run everywhere but if you have
// HTTPS on your domain then replace it by 1 to lock it!
'secure' => $is_https ? 1 : 0, // IMPORTANT: Replace by 1 if you have both HTTP and HTTPS enabled.
// Don't let JavaScript access the session cookie.
'httponly' => 1,
// If another site has a link pointing to your website then don't send
// the session cookie (POST or GET). This mitigates somes kind of attacks.
'samesite' => 'Strict',
];
// Apply all the session cookie settings without ini_set() for maximum portability:
session_name($session_cookie_name);
session_set_cookie_params($session_cookie_options); // Since PHP 7.3 only
session_start();
// If the session cookie has been sent by the browser then it might have an expiration
// date to early (because it is set only once at the creation of the session).
// Instead we would like it to expire with our lifetime since the last user's
// action. To do that we have to use setcookie() to resend the cookie in order
// to update/overwrite it to have a new expiration date in the browser.
if (isset($_COOKIE[$session_cookie_name]) && $_COOKIE[$session_cookie_name] == session_id()) {
$cookie_options = $session_cookie_options;
unset($cookie_options['lifetime']); // This one is replaced by expires below.
$cookie_options['expires'] = time() + COOKIE_LIFETIME;
setcookie($session_cookie_name, session_id(), $cookie_options);
}
// Now that HTTP headers have been set, we are allowed to start printing output.
// If the user is already logged and his caddie is empty then fill it with some
// random stuff. It will stay saved until the session expires.
if (isset($_SESSION['session_creation_date']) && !isset($_SESSION['shop_caddie'])) {
$_SESSION['shop_caddie'] = [
'T-shirt' => [
'quantity' => rand(1, 3),
'color' => 'red',
],
'Beer' => [
'quantity' => (['2dl', '3dl', '5dl'])[rand(0, 2)],
]
];
}
// If the session is empty, let's init it with the creation date for the showcase.
if (empty($_SESSION)) {
$_SESSION['session_creation_date'] = date('r');
}
print 'Recieved cookies from the browser = ' . var_export($_COOKIE, true) . "\n\n";
print 'Session data = ' . var_export($_SESSION, true) . "\n\n";

Related

How in adminer to increase current session on login?

Using adminer-4.7.7 with plugin login-password-less.php
I found a way how to enter adminer without credentials entered.
But entering adminer I would like to keep the current session as far as possible(including
current db and table opened), even after browse closed/opened next day...
Has adminer session time parameter/tools?
That is for my home laptop ( kununtu18, apache 2, php 7.4), so security breaks are ignored...
apache config decisions also possible.
How can I do it ?
MODIFIED :
I tried to increase gc_maxlifetime as in Jasar Orion code, but failed
I modified session block in adminer/include/bootstrap.inc.php as:
global $adminer, $connection, $driver, $drivers, $edit_functions, $enum_length, $error, $functions, $grouping, $HTTPS, $inout, $jush, $LANG, $langs, $on_actions, $permanent, $structured_types, $has_token, $token, $translations, $types, $unsigned, $VERSION; // allows including Adminer inside a function
if (!$_SERVER["REQUEST_URI"]) { // IIS 5 compatibility
$_SERVER["REQUEST_URI"] = $_SERVER["ORIG_PATH_INFO"];
}
if (!strpos($_SERVER["REQUEST_URI"], '?') && $_SERVER["QUERY_STRING"] != "") { // IIS 7 compatibility
$_SERVER["REQUEST_URI"] .= "?$_SERVER[QUERY_STRING]";
}
if ($_SERVER["HTTP_X_FORWARDED_PREFIX"]) {
$_SERVER["REQUEST_URI"] = $_SERVER["HTTP_X_FORWARDED_PREFIX"] . $_SERVER["REQUEST_URI"];
}
$HTTPS = ($_SERVER["HTTPS"] && strcasecmp($_SERVER["HTTPS"], "off")) || ini_bool("session.cookie_secure"); // session.cookie_secure could be set on HTTP if we are behind a reverse proxy
#ini_set("session.use_trans_sid", false); // protect links in export, # - may be disabled
if (!defined("SID")) {
session_cache_limiter(""); // to allow restarting session
session_name("adminer_sid"); // use specific session name to get own namespace
// $params = array(0, preg_replace('~\?.*~', '', $_SERVER["REQUEST_URI"]), "", $HTTPS);
if (version_compare(PHP_VERSION, '5.2.0') >= 0) {
$params[] = true; // HttpOnly
}
$lifetime = time() + 97 * 24 * 60 * 60;
$params = array($lifetime, preg_replace('~\?.*~', '', $_SERVER["REQUEST_URI"]), "", $HTTPS);
ini_set('session.gc_maxlifetime', 99600);
call_user_func_array('session_set_cookie_params', $params); // ini_set() may be disabled
session_set_cookie_params(99600);
session_start();
}
It is invalid way? Which way is valid?
Thanks!
If you open file adminer/adminer/include/bootstrap.inc.php:57 you could see the following code:
call_user_func_array('session_set_cookie_params', $params); // ini_set() may be disabled
According to documentation this methods sets session lifetime. By default it set to 0, which means that session will be destroyed when browser is closed.
I suppose, you could set another value you want:
$lifetime = time() + 7 * 24 * 60 * 60;
$params = array($lifetime, preg_replace('~\?.*~', '', $_SERVER["REQUEST_URI"]), "", $HTTPS);
This could be a problem of permission,
can you check in your phpinfo() the value of “session.save_path”, if you are working on localhost this is normally C:\xampp\tmp.
If you are working on ubuntu the session folder should be /var/lib/php/session, if the folder session doesn't exist you should navigate to /var/lib/php/ and create the folder with:
mkdir session
then you need to extend the permission to user www-data, with:
sudo chown -R www-data:www-data /var/lib/php/session
Good luck!
Session timeout is a notion that has to be implemented in code if you want strict guarantees; that's the only way you can be absolutely certain that no session ever will survive after X minutes of inactivity.
If relaxing this requirement a little is acceptable and you are fine with placing a lower bound instead of a strict limit to the duration, you can do so easily and without writing custom logic.
Convenience in relaxed environments: how and why
If your sessions are implemented with cookies (which they probably are), and if the clients are not malicious, you can set an upper bound on the session duration by tweaking certain parameters. If you are using PHP's default session handling with cookies, setting session.gc_maxlifetime along with session_set_cookie_params should work for you like this:
// server should keep session data for AT LEAST 1 hour
ini_set('session.gc_maxlifetime', 3600);
// each client should remember their session id for EXACTLY 1 hour
session_set_cookie_params(3600);
session_start(); // ready to go!
This works by configuring the server to keep session data around for at least one hour of inactivity and instructing your clients that they should "forget" their session id after the same time span. Both of these steps are required to achieve the expected result.
If you don't tell the clients to forget their session id after an hour (or if the clients are malicious and choose to ignore your instructions) they will keep using the same session id and its effective duration will be non-deterministic. That is because sessions whose lifetime has expired on the server side are not garbage-collected immediately but only whenever the session GC kicks in.
GC is a potentially expensive process, so typically the probability is rather small or even zero (a website getting huge numbers of hits will probably forgo probabilistic GC entirely and schedule it to happen in the background every X minutes). In both cases (assuming non-cooperating clients) the lower bound for effective session lifetimes will be session.gc_maxlifetime, but the upper bound will be unpredictable.
If you don't set session.gc_maxlifetime to the same time span then the server might discard idle session data earlier than that; in this case, a client that still remembers their session id will present it but the server will find no data associated with that session, effectively behaving as if the session had just started.
Certainty in critical environments
You can make things completely controllable by using custom logic to also place an upper bound on session inactivity; together with the lower bound from above this results in a strict setting.
Do this by saving the upper bound together with the rest of the session data:
session_start(); // ready to go!
$now = time();
if (isset($_SESSION['discard_after']) && $now > $_SESSION['discard_after']) {
// this session has worn out its welcome; kill it and start a brand new one
session_unset();
session_destroy();
session_start();
}
// either new or old, it should live at most for another hour
$_SESSION['discard_after'] = $now + 3600;
Session id persistence
So far we have not been concerned at all with the exact values of each session id, only with the requirement that the data should exist as long as we need them to. Be aware that in the (unlikely) case that session ids matter to you, care must be taken to regenerate them with session_regenerate_id when required.

PHP session logs out before session cookie expires

I have set up cookie lifetime to last a complete day, but after 15-20 mins of idle time, I get logged out anyways. The strangest thing is that everything runs fine on localhost, but when I took my website live, I started experiencing this problem with the same exact code.
I read on stackoverflow that it could be related to session.gc_maxlifetime, so I have even edited that on the .htaccess level. I have changed it from 1440 to 86400, but the problem still persists.
Here is the rundown of my code.
When a user logs in, I check if the user already has a cookie named 'AUTHID'. If the user does, I first delete it.
if (isset($_COOKIE['AUTHID'])) {
unset($_COOKIE['AUTHID']);
setcookie('AUTHID', null, -1, '/');
}
After that, depending on if the user selected Remember Me option, I set the cookie lifetime value, and it creates a cookie that I can see in Chrome Settings with absolutely correct expiration time.
session_name('AUTHID');
ini_set('session.cookie_httponly', 1);
if(isset($_POST['remember-me'])) {
ini_set('session.gc_maxlifetime', 604800);
session_set_cookie_params(604800,"/");
} else {
ini_set('session.gc_maxlifetime', 86400);
session_set_cookie_params(86400,"/");
}
session_start();
Lastly, I have a php function to check if the user is logged in on every single page:
$rel_url = "$_SERVER[REQUEST_URI]";
session_name('AUTHID');
session_start();
if(!isset($_SESSION['user_id'])) {
if (strpos($rel_url, 'login=success') !== false) {
header('Location: index.php');
}
header('Location: login-with-bg.php?access-denied=logged-out');
exit();
}
This works perfectly fine on my localhost, but when I uploaded this code on my hosting server, even though the cookie is still being created with correct expiration date, but if my browser is idle for 15-20 mins, my session gets timed out.
EDIT: from an article, I got an idea of making AJAX calls every 10 mins or so, and that works when the browser is open. However, I need a complete method that works even if the browser is closed.
EDIT2: The AJAX code that I have for keeping the session alive:
function keep_alive() {
$.get('index.php',null)
}
keep_alive_interval = setInterval(keep_alive, 600000)
A few notes:
Session and ajax is a tricky thing. Be sure to close your session when doing an ajax call so it writes changes to your session. (register_shutdown_function("session_write_close");)
In this case there is no real use in changing the sessionname (default will do).
The AUTHID cookie stores your session_id which corresponds to your session. This has to be set also. No need to manually set the cookie
This is working for me on the server but not on local machines
if ($_SERVER['SERVER_ADDR'] != '127.0.0.1'){ // Only use custom session on server. use default settings on local machine
register_shutdown_function("session_write_close"); // write your changes done with ajax before your session opens again
// some security settings
ini_set("session.use_strict_mode", 1);
ini_set("session.cookie_httponly", 1);
ini_set("session.cookie_secure", 1);
ini_set("session.use_only_cookies", 1);
ini_set("session.gc_maxlifetime",60 * 60 * 24 * 14); // 2 weeks
session_set_cookie_params(60 * 60 * 24 * 14,"/",".yourdomain.com"); // 2 weeks
session_name("AUTHID");
if(isset($_COOKIE['AUTHID'])){
session_id($_COOKIE['AUTHID']);
}
}
session_start();

What is the best way to make "remember me" under php when using native sessions?

Previously i was creating additional cookie "rememberme" with unique hash, that was stored in the database, mapped to the user id.
If user had such cookie - website tried to find it's value in database, and if it was found session was setting up.
Later, developing new project i thought that it is maybe not very secure to generate this unique hash by myself, and keeping two cookies (native "PHPSESSID" + my "rememberme") for one operation (user identification) is overkill.
Maybe there is a way to setup not global session lifetime, but to setup it individually for different user sessions... or maybe it is better to keep user sessions in the database, mapped to the userid?
UPDATE 1
I thought if it is so hard to make "remember me" button, we can go another way - to make "Not my computer button". Idea is to set default cookie_lifetime for a week in php.ini (for example), and if user checkes this checkbox - we will set cookie_lifetime into zero using session_set_cookie_params function.
So, 1st question is - will session_set_cookie_params affect other users cookies (in documentation it is said, that session_set_cookie_params options will have effect until php process will be executing)
2d question is that if session_set_cookie_params is not affecting global settings, will session regeneration affect users, that don't want to keep a long-life cookie?
UPDATE 2: [Question 1 answer]
Just tested session_set_cookie_params function.
I wrote a script, that sets session cookie lifetime into zero using session_set_cookie_params and then executing for 30 seconds:
if ($_GET['test']) {
session_set_cookie_params (0);
while (true) {
sleep(1);
}
}
session_start();
So, in first browser i just started this script with ?test=1 parameter, just after that (while this script was executing) i started this script without parameters in the second browser. The answer is no - second browser's cookie was not affected. It had lifetime, that was specified in php.ini
UPDATE 3: [Question 2 answer]
Then, i've tried to check if regeneration affects session cookie lifetime, that was set by session_set_cookie_params.
Yes, it affects. If i set session cookie with customized lifetime, that was set by session_set_cookie_params, and then call session_regenerate_id(), cookie will have lifetime, set in php.ini
But, if we set session_set_cookie_params (0) before calling session_regenerate_id(), our cookie will have correct lifetime.
So, that's it! That was easy! 8)
Thank you, ladies and gentlemen!
If you want to do this only using sessions you can do the following if the user wants to be remembered:
if((isset($_POST['remember_me']) && $_POST['remember_me']) || ($_COOKIE['remember_me']) && $_COOKIE['remember_me'])) {
// store these cookies in an other directory to make sure they don't
// get deleted by the garbage collector when starting a "non-remeber-me"-session
$remember_me_dir = ini_get('session.save_path') . DS . "remember_me_sessions";
// create the directory if it doesn't exist
if (!is_dir($remember_me_dir)) {
mkdir($remember_me_dir);
}
// set the php.ini-directive (temporarily)
ini_set('session.save_path', $remember_me_dir);
// define lifetime of the cookie on client side
$expire_cookie = 60 * 60 * 24 * 30; // in seconds
session_set_cookie_params($expire_cookie);
// lifetime of the cookie on server side
// session file gets deleted after this timespan
// add a few seconds to make sure the browser deletes
// the cookie first.
$garbage_in = $expire_cookie + 600; // in seconds
// set the php-ini directive for the garbage collector of the session files.
ini_set('session.gc_maxlifetime', $garbage_in);
// send an additional cookie to keep track of the users
// which checked the 'remember_me' checkbox
setcookie('remember_me', 1, time() + $expire_cookie);
}
// now we are ready to start the session
// For all the users which didn't choose to check the 'remember_me' box
// the default settings in php.ini are used.
session_start();
Here you can read more about the session related php.ini-directives
As it was so hard to make "remember me" checkbox functionality, i came to another way, using only one cookie.
PREPARATION
1) I've prepared a form with three inputs:
"login" input [type=text]: user's login
"password" input [type=password]: user's password
"not my computer" input [type=checkbox]: that will tell us to use session cookie with lifetime = 0 (cookie must be deleted when browser will be closed)
2) I've set session.cookie_lifetime = 100500 to keep long-life cookies by default.
COOKIE SETUP
So, after user submits the form, we check - if he has selected to use short sessions - we call session_set_cookie_params(0) before setting session cookie to him (before actually using session_start()).
COOKIE REGENERATION
Then, when we need to regenerate session cookie, we can also do this easily with session_regenerate_id() function.
But we need to remember, that this function will re-set session cookie lifetime from php.ini by default.
So, we need also to call session_set_cookie_params() before regenerating a cookie.
BTW, You can store custom session cookie lifetime in $_SESSION.
It will look like this:
// Form handling, session setup
if ($_POST['not-my-computer']) {
session_set_cookie_params(0);
session_start();
$_SESSION['expires'] = 0;
}
// Session regeneration
if (isset($_SESSION['expires'])) {
session_set_cookie_params(0);
session_regenerate_id();
}
Details for this answer (and more deep explanations) you can find in the question text (while i was testing, i added answers/tests results there)

Can't always read session cookie

I have a page (mypage.html) which sets a cookie as follows:
setcookie ("sessionid", md5 (uniqid (rand())));
Now, at the top of an include which displays the site header I have the following:
echo "cookie is ". $_COOKIE['sessionid'];
When I am on mypage.html, which includes the header, the echo command displays the cookie name, as it should...e.g.
cookie is 4d40102ff2d2268d907dd31debc411e2 cookie is 4d40102ff2d2268d907dd31debc411e2
But if I move aeway from the page which set the cookie, all I see is
cookie is
with no name - If I go back to mypage.html it reads it again with no problem. I have no clue how this can happen?? Any ideas?
Set an explicit path for the cookie. The default is the current directory only, so if you navigate to a script in another directory, the cookie won't be sent back by the browser.
// Cookie is valid for all paths ( / ) in the current domain
// This also has an explicit expiry time of 1 hour from the time it's set...
setcookie ("sessionid", md5 (uniqid (rand())), time() + 3600, "/");
It's a little unusual to be setting your own session cookies though, when simply initiating a session handles it for you:
session_start();
// Id is set for you...
echo session_id();

How to kill a/all php sessions?

I have a very basic php session login script. I want to force logout of a certain user or force logout of all users.
How can I read all sessions made to my website, and destroy some or all sessions?
You could try to force PHP to delete all the sessions by doing
ini_set('session.gc_max_lifetime', 0);
ini_set('session.gc_probability', 1);
ini_set('session.gc_divisor', 1);
That forces PHP to treat all sessions as having a 0-second lifetime, and a 100% probability of getting cleaned up.
The drawback is that whichever unlucky user runs this first will get a long pause while PHP does cleanup, especially if there's a lot of session files to go through.
For one particular user, you'd have to add some code to your session handler:
if ($_SESSION['username'] == 'user to delete') {
session_destroy();
}
PHP's garbage collector isn't controllable, so you can't give it parameters such as "delete all sessions except for user X's". It looks strictly at the last-modified/last-accessed timestamps on the session files and compares that to the max_lifetime setting. It doesn't actually process the session data.
You can use session_save_path() to find the path where PHP saves the session files, and then delete them using unlink().
Updated - Aug 2012
This code is based from the official PHP site, and another well written snippet on SO.
<?php
// Finds all server sessions
session_start();
// Stores in Array
$_SESSION = array();
// Swipe via memory
if (ini_get("session.use_cookies")) {
// Prepare and swipe cookies
$params = session_get_cookie_params();
// clear cookies and sessions
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
// Just in case.. swipe these values too
ini_set('session.gc_max_lifetime', 0);
ini_set('session.gc_probability', 1);
ini_set('session.gc_divisor', 1);
// Completely destroy our server sessions..
session_destroy();
?>
Works well. Servers like NGinx you can turn off, clean cache, swipe memory reset, clear logs etc and generally remove temp usage. Even drop the limits of memory.
Clearling all sessions at once would require first knowing which session.save_handler is being used to store sessions and locating the session.save_path in order to delete all sessions. For deleting the current session only, refer to the documentation for session_destroy().
Here are some common examples for deleting all sessions using standard file and memcached save handlers:
Using file save handler
foreach(glob(ini_get("session.save_path") . "/*") as $sessionFile) {
unlink($sessionFile);
}
Using memcached save handler
$memcached = new Memcached;
$memcached->addServers($listOfYourMemcachedSesssionServers);
// Memcached session keys are prefixed with "memc.sess.key." by default
$sessionKeys = preg_grep("#^memc\.sess\.key\.#", $memcached->getAllKeys());
$memcached->deleteMulti($sessionKeys);
Of course, you might want to consider only doing this out of band from your normal HTTP client requests, since cleaning up large session storage may take some time and have inadvertent side effects in a normal request life cycle.
I found this code very helpful and it really worked for me
<?php
$path = session_save_path();
$files = glob($path.'/*'); // get all file names
foreach($files as $file){ // iterate files
if(is_file($file))
unlink($file); // delete file
}
?>
It depends on your session storage.
If you're using PHP session storage, then they may be in the temporary directory of your server. Deleting the selected files will "kill" the session. However if your server is in running state, that session file may be occupied by HTTP process and you won't be able to delete it. Just look at the image below. File named as starting with "+~" are all session files.
A nicer solution is to use a database session storage and delete the selected sessions from there. You can check out HTTP_Session2 which has multiple containers.
I will create a txt file containing the token which has the same value as the generated login session as a comparison every time the user is logged in:
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$token = sha1(uniqid(mt_rand(), true));
if($everything_is_valid) {
// Set login session
$_SESSION[$_POST['username']] = $token;
// Create token file
file_put_contents('log/token.' . $_POST['username'] . '.txt', $token);
// Just to be safe
chmod('log/token.' . $_POST['username'] . '.txt', 0600);
}
}
Checks for logged in user(s):
if(isset($_SESSION['charlie']) && file_exists('log/token.charlie.txt') && $_SESSION['charlie'] == file_get_contents('log/token.charlie.txt')) {
echo 'You are logged in.';
}
So, if you want to force this charlie user to be logged out, simply remove the token file:
// Force logout the `charlie` user
unlink('log/token.charlie.txt');
Taufik's answer is the best i could find.
However, you can further modify it
After authenticating the user and creating the session variables, add these lines:
$token = "/sess_" . session_id();
file_put_contents('log/' . $_SESSION['id'] . '.txt', $token);
If you need to force the user to log out during a cronjob or by an admin request:
$path = session_save_path();
$file = file_get_contents('log/xxx.txt'); // xxx is user's id
$url = $path.$file;
unlink($url);
remove all session variables
session_unset();
destroy the session
session_destroy();

Categories