Recently I've noticed that many blank sessions are being created, I'm not sure why though as I believe I'm doing everything the correct way.
At the moment we create a session when a user either logs in or registers, we then check whether a user is logged in with an isset($_COOKIE['auth'])
that belongs to the session created during login or register.
If that cookie is present then we start a session, this helps us avoid starting thousands of sessions for unregistered users and creating a huge amount of session files.
Session Settings:
php file
session_save_path("/home/user/sessions");
session_set_cookie_params("86400", "/");
session_name("auth");
php.ini
session.gc_maxlifetime = 90000
session.cookie_lifetime = 90000
session.use_trans_sid = 0
session.use_only_cookies = 1
Create Login Session (On Successful login)
session_start();
session_regenerate_id(true);
$_SESSION['userId'] = $userId;
$_SESSION['created'] = time();
session_write_close();
header("Location: $_SERVER[HTTP_REFERER]");
Checking whether a session should be resumed
We then check whether to start a session or not for a user based on whether the auth
session cookie is set.
It will only be set if the user has registered or logged in before:
if(isset($_COOKIE['auth'])){
session_start();
session_write_close();
}
Check if user is logged in
To check if a user is logged in we then use a function:
function isAuthenticated(){
if (!isset($_SESSION['userId']))
return false;
else
return true;
}
Log Out
function logOut(){
session_start();
session_destroy();
setcookie('auth', "", 0);
unset($_SESSION);
unset($_COOKIE['auth']);
return true;
}
For some reason though I am getting lots of empty (filesize 0) session files in the session folder.
Where are these coming from?
Does session_regenerate_id(true)
create a new session file and leave the old session file empty? That is the only reason I can think of for the empty session files?
bool session_regenerate_id([bool $delete_old_session = false]);
view php manual for more information.
session_regenerate_id()
will replace the current session id with a new one, and keep the current session information.
the old session file is kept and a new session file is generated every time that session_register_id()
is ran. session_register_id()
creates a new session with a new session_id but retains the old session information, so yes, your session_register_id()
is keeping the old session files to null after updating the information to the new session file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With