PHP Sessions and session_regenerate_id - php

I've been trying to solve this problem for many weeks now.
I've made a class to secure PHP sessions, and it works fine unless someone is trying to perform registration (its the problem #2) and if some of the functionality disabled (which is causing #2 to happen), the rest of the website work just fine.
So here are the problems:
session_regenerate_id - commented out
From here, everything works just fine, except for captcha creation mechanism (only on registration page), for login page it works just fine
session_regenerate_id(true) - uncommented
In here, registration works just fine, no problems, no captcha issues, but after few refreshes of the page, session just gone, so user need to log in for 6 more refreshes and $_SESSION again sets to null
I know where the problem might be, but i dont know how to solve it.
I have a private static function, which is called straight after session_start() is called
private static function GenerateSessionData()
{
$_SESSION['loggedin'] = '';
$_SESSION['username'] = '';
$_SESSION['remember_me'] = '';
$_SESSION['preferredlanguage'] = '';
$_SESSION['generated_captcha'] = '';
}
This is done to pre-define variables to be used by session (and i'm 90% sure that this is why session goes blank after).
The thing im not sure about, is WHY.
Here is the full session class:
<?php
Class Session
{
public static $DBConnection;
private static $SessionCreated = false;
public function __construct($Database)
{
session_set_save_handler(array($this, 'Open'), array($this, 'Close'), array($this, 'Read'), array($this, 'Write'), array($this, 'Destroy'), array($this, 'GarbageCollector'));
register_shutdown_function('session_write_close');
Session::$DBConnection = $Database::$Connection;
}
private static function GenerateSessionData()
{
$_SESSION['loggedin'] = '';
$_SESSION['username'] = '';
$_SESSION['remember_me'] = '';
$_SESSION['preferredlanguage'] = '';
$_SESSION['generated_captcha'] = '';
}
public static function UpdateSession($Data)
{
if(!isset($_SESSION['loggedin']))
Session::GenerateSessionData();
foreach($Data as $key=>$value)
$_SESSION[$key] = $value;
}
public static function GenerateCSRFToken()
{
$InitialString = "abcdefghijklmnopqrstuvwxyz1234567890";
$PartOne = substr(str_shuffle($InitialString),0,8);
$PartTwo = substr(str_shuffle($InitialString),0,4);
$PartThree = substr(str_shuffle($InitialString),0,4);
$PartFour = substr(str_shuffle($InitialString),0,4);
$PartFive = substr(str_shuffle($InitialString),0,12);
$FinalCode = $PartOne.'-'.$PartTwo.'-'.$PartThree.'-'.$PartFour.'-'.$PartFive;
$_SESSION['generated_csrf'] = $FinalCode;
return $FinalCode;
}
public static function ValidateCSRFToken($Token)
{
if(isset($Token) && $Token == $_SESSION['generated_csrf'])
{
unset($_SESSION['generated_csrf']);
return true;
}
else
return false;
}
public static function UnsetKeys($Keys)
{
foreach($Keys as $Key)
unset($_SESSION[$Key]);
}
public static function Start($SessionName, $Secure)
{
$HTTPOnly = true;
$Session_Hash = 'sha512';
if(in_array($Session_Hash, hash_algos()))
ini_set('session.hash_function', $Session_Hash);
ini_set('session.hash_bits_per_character', 6);
ini_set('session.use_only_cookies', 1);
$CookieParameters = session_get_cookie_params();
session_set_cookie_params($CookieParameters["lifetime"], $CookieParameters["path"], $CookieParameters["domain"], $Secure, $HTTPOnly);
session_name($SessionName);
session_start();
session_regenerate_id(true);
if(!Session::$SessionCreated)
if(!isset($_SESSION['loggedin']))
Session::GenerateSessionData();
Session::$SessionCreated = true;
}
static function Open()
{
if(is_null(Session::$DBConnection))
{
die("Unable to establish connection with database for Secure Session!");
return false;
}
else
return true;
}
static function Close()
{
Session::$DBConnection = null;
return true;
}
static function Read($SessionID)
{
$Statement = Session::$DBConnection->prepare("SELECT data FROM sessions WHERE id = :sessionid LIMIT 1");
$Statement->bindParam(':sessionid', $SessionID);
$Statement->execute();
$Result = $Statement->fetch(PDO::FETCH_ASSOC);
$Key = Session::GetKey($SessionID);
$Data = Session::Decrypt($Result['data'], $Key);
return $Data;
}
static function Write($SessionID, $SessionData)
{
$Key = Session::GetKey($SessionID);
$Data = Session::Encrypt($SessionData, $Key);
$TimeNow = time();
$Statement = Session::$DBConnection->prepare('REPLACE INTO sessions (id, set_time, data, session_key) VALUES (:sessionid, :creation_time, :session_data, :session_key)');
$Statement->bindParam(':sessionid', $SessionID);
$Statement->bindParam(':creation_time', $TimeNow);
$Statement->bindParam(':session_data', $Data);
$Statement->bindParam(':session_key', $Key);
$Statement->execute();
return true;
}
static function Destroy($SessionID)
{
$Statement = Session::$DBConnection->prepare('DELETE FROM sessions WHERE id = :sessionid');
$Statement->bindParam(':sessionid', $SessionID);
$Statement->execute();
Session::$SessionCreated = false;
return true;
}
private static function GarbageCollector($Max)
{
$Statement = Session::$DBConnection->prepare('DELETE FROM sessions WHERE set_time < :maxtime');
$OldSessions = time()-$Max;
$Statement->bindParam(':maxtime', $OldSessions);
$Statement->execute();
return true;
}
private static function GetKey($SessionID)
{
$Statement = Session::$DBConnection->prepare('SELECT session_key FROM sessions WHERE id = :sessionid LIMIT 1');
$Statement->bindParam(':sessionid', $SessionID);
$Statement->execute();
$Result = $Statement->fetch(PDO::FETCH_ASSOC);
if($Result['session_key'] != '')
return $Result['session_key'];
else
return hash('sha512', uniqid(mt_rand(1, mt_getrandmax()), true));
}
private static function Encrypt($SessionData, $SessionKey)
{
$Salt = "06wirrdzHDvc*t*nJn9VWIfET+|co*pm~CbtT5P*S2IPD-VmEfd+CX2wrvZ";
$SessionKey = substr(hash('sha256', $Salt.$SessionKey.$Salt), 0, 32);
$Get_IV_Size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$IV = mcrypt_create_iv($Get_IV_Size, MCRYPT_RAND);
$Encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $SessionKey, $SessionData, MCRYPT_MODE_ECB, $IV));
return $Encrypted;
}
private static function Decrypt($SessionData, $SessionKey)
{
$Salt = "06wirrdzHDvc*t*nJn9VWIfET+|co*pm~CbtT5P*S2IPD-VmEfd+CX2wrvZ";
$SessionKey = substr(hash('sha256', $Salt.$SessionKey.$Salt), 0, 32);
$Get_IV_Size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$IV = mcrypt_create_iv($Get_IV_Size, MCRYPT_RAND);
$Decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $SessionKey, base64_decode($SessionData), MCRYPT_MODE_ECB, $IV);
return $Decrypted;
}
}
?>
And i cant exclude that private static function (the first one mentioned) since then i wont be able to set the variables.
And you might say: 'but there is a UpdateSession method'....
Yeah.... kinda.... but the thing is, due to i guess lack of my knowledge, i messed up script somewhere, and the logic goes wrong.
Here are the links (to maybe simplify understanding):
Sessions.FreedomCore.php - Sessions Class
String.FreedomCore.php - Captcha Generation (pointed to exact line)
pager.php - Account Creation Process (works only with session_regenerate_id)
pager.php - Captcha display Process (works always in some cases)
pager.php - Perform Login Case (No issues in any case for some reason)
If you like super interested in how this actually works (i mean how it deauthorize users after 4 refreshes)
Please head over here
Username: test
Password: 123456
So the question is:
How to modify my class, to save session data with session_regenerate_id(true) with usage of current methods and to prevent it to be flushed after session_regenerate_id is called.
These links are pointing directly to problematic areas of the script.
Any help is really appreciated.
Thank you very much for any help!

You are experiencing what I call Cookie Race Condition.
As your are using session_regenerate_id(true) PHP creates a new session id (containing the data of the old session) and deletes the old session from your database for each request.
Now your website contains contains many elements which need to be loaded, e.g. /pager.php or /data/menu.json. And each time the browser gets assigned a new session id. Normally not a problem, but modern browsers do requests in parallel:
pager.php is requested with session_id = a
data/menu.json is requested with session_id = a
pager.php drops sessions_id = a and returns session_id = b to my browser.
data/menu.json cannot find session_id = a in the database and assumes I'm a new visitor and gives me the session_id = c
Now it depends which request is received and parsed by the browser in which order.
Case A data/menu.json is parsed first: the browser stores session_id = c. Then the response of pager.php is parsed and the browser overrides session_id with b. For any next request it will use session_id = b.
Case B pager.php is parsed first and then data/menu.json. The browser stores now session_id = c and you are logged out.
This explains why it's sometimes working (e.g., 4 or 6 refreshes) and sometimes not.
Conclusion: don't use session_regenerate_id(); without a very good reason!
Please raise a new question why the captcha creation mechanism does not work on registration page but on login page.
Some notes on your encryption.
Do NOT use AES with ECB Mode. This weakens the encryption.
You store the encryption key next to your data. Your encryption just blew up.

Related

PHP Auto Login after Registration

I'm having some issues with a request from my boss.
I'm using the http://www.html-form-guide.com/ Registration forms he has created for use (I've attached the link just in case anyone want to use or look at it)
So I'm pretty new to PHP, but I've been gaining a crazy amount of knowledge.
Here is my problem - I need to make this form Register the user than Login Automatically. (This form has a Email confirmation system)
So I've managed to bypass the Email Confirmation and get the user to register, but I can't seem to figure out how to get auto login.
Here is what I've traced in the code:
function RegisterUser()
{
if(!isset($_POST['submitted']))
{
return false;
}
$formvars = array();
if(!$this->ValidateRegistrationSubmission())
{
return false;
}
$this->CollectRegistrationSubmission($formvars);
if(!$this->SaveToDatabase($formvars))
{
return false;
}
/*if(!$this->SendUserConfirmationEmail($formvars))
{
return false;
}*/
$this->SendAdminIntimationEmail($formvars);
$this->AutoLogin($formvars);// My call
return true;
}
This will pull in the name, email and password - put them in an array then send it off for validation and sanitation. I've placed a call function here.
After which I'll need to manually login with:
function Login()
{
if(empty($_POST['email']))
{
$this->HandleError("Email is empty!");
return false;
}
if(empty($_POST['password']))
{
$this->HandleError("Password is empty!");
return false;
}
$email = trim($_POST['email']);
$password = trim($_POST['password']);
if(!isset($_SESSION)){ session_start(); }
if(!$this->CheckLoginInDB($email,$password))
{
return false;
}
$_SESSION[$this->GetLoginSessionVar()] = $email;
return true;
}
So I took the last portion of the login function and made:
function AutoLogin(&$formvars)
{
$email = trim($formvars['email']);
$password = trim($formvars['password']);
if(!isset($_SESSION)){ session_start(); }
if(!$this->CheckLoginInDB($email,$password))
{
return false;
}
$_SESSION[$this->GetLoginSessionVar()] = $email;
return true;
}
I did an echo $email; echo $password; exit; test and I can see that the email and password are appearing. But the "Session" (I think) is not starting or the Check Login is not getting the data.
function CheckLogin()
{
if(!isset($_SESSION)){ session_start(); }
$sessionvar = $this->GetLoginSessionVar();
if(empty($_SESSION[$sessionvar]))
{
return false;
}
return true;
}
Now I see the is a CheckLoginInDB which is:
function CheckLoginInDB($email,$password)
{
if(!$this->DBLogin())
{
$this->HandleError("Database login failed!");
return false;
}
$email = $this->SanitizeForSQL($email);
$pwdmd5 = md5($password);
$qry = "Select name, email, pagecode, welcome from $this->tablename where email='$email' and password='$pwdmd5' and confirmcode='y'";
$result = mysql_query($qry,$this->connection);
if(!$result || mysql_num_rows($result) <= 0)
{
$this->HandleError("Error logging in. The email or password does not match");
return false;
}
$row = mysql_fetch_assoc($result);
$_SESSION['name_of_user'] = $row['name'];
$_SESSION['email_of_user'] = $row['email'];
$_SESSION['pagecode_of_user'] = $row['pagecode'];
$_SESSION['welcome_user'] = $row['welcome'];
return true;
}
What I can gather from this, its just a standard checking the database to see if this user exists and returning the results.
I've searching through stackoverflow and can't seem to see an answer to my problem.
I looked into Cookies, but I don't think that is something I really need here.
My questions are:
How can I make this bad boy start the session on registration?
Is my thinking on calling the AutoLogin(&$formvars) the right idea?
Have I gone wrong with this AutoLogin function syntax?
Just in case here is the GetLoginSessionVar():
function GetLoginSessionVar()
{
$retvar = md5($this->rand_key);
$retvar = 'usr_'.substr($retvar,0,10);
return $retvar;
}
It's a pity I can't attached the file I'm working on, but if you need any further code snippets let me know and I'll be sure to Edit this straight away!
But the "Session" (I think) is not starting or the Check Login is not
getting the data.
Is my thinking on calling the AutoLogin(&$formvars) the right idea?
Have I gone wrong with this AutoLogin function syntax?
It's not something wrong with the syntax, otherwise the code wouldn't even be compiled. Nevertheless I believe it's not the right idea.
You need to understand what's the problem before trying to fix it.
Debug the code. Use xdebug. If it's installed and active, you can use IDEs (e.g.: Visual Studio Code) to easily debug the code. Add breakpoints where you suspect there's something wrong.
If you don't want to use xdebug, you can add temporarily echoes or var_dumps to check if some areas of the code are processed and check some relevant values.
Also enable all errors reports and use a logger.
If the session is started after any output, there should be some warning.
Handle the errors and throw exceptions.
http://php.net/manual/en/function.error-log.php
http://php.net/manual/en/function.syslog.php
https://jtreminio.com/2012/07/xdebug-and-you-why-you-should-be-using-a-real-debugger/
session_start() works after output being sent
http://php.net/manual/en/function.error-reporting.php
You don't need to use the & in AutoLogin(&$formvars) if you're not changing the argument $formvars (you're just reading it).
You don't need to set session variables with all the user data. Create some structure (a class, an array, ...) with the user data outside those function and change those. AutoLogin should update that structure, something like this:
<?php
if (!$_SESSION) {
session_start();
}
$currentUser = array();
function getUserFromID($userID)
{
//TODO implement function
return $user;
}
function AutoLogin()
{
global $currentUser;
if(!empty($_SESSION['userID'])) {
return false;
}
$user = getUserFromID($_SESSION['userID']);
if (empty($user)) {
return false;
}
$currentUser = $user;
return true;
}
Maybe the session is not initialised before CheckLoginInDB is invoked (make var_dump($_SESSION); to check it). Use the $_SESSION only to save the user ID (or email) and read it to retrieve the user data.

Forcing login on phpMyAdmin using cookies

Hello again StackExchange users. Todays problem is a little more complex then usual for my. I am developing a web based hosting panel for a server that my company just set up and they would like to manage web pages from the internet. The rest of the control panel is working great but this one third-party app is really bugging me, and that app is phpMyAdmin!
I want the user to be able to log into the "cPanel" of their website (note: we are not using cPanel or any previous software) and just click the phpMyAdmin link and be logged in already to their own specific database. When they login, I am passing their sql database account details into a cookie using the same encryption type that they have for phpMyAdmin. Viewing the cookie shows that the cookie is formatted correctly and they should be logged onto the system
The problem is when they click on the link to go to the phpMyAdmin page, they still get the login form even though the cookie is already set and appears to be correct. There is no error message or even a please relog in message with the system.
I have included my code for my CookieAuth class below so you guys can look at it. It's really frustrating since the cookies seem to be the only way I can log them in properly and there's not many documented examples on how to do this anywhere else.
class CookieAuth {
private $_cookie_iv = null;
public function createPMAsession($username, $password, $blowfish_key) {
setCookie('pmaUser-1', $this->cookieEncrypt($username, $blowfish_key), time()+3600, "/phpmyadmin/");
setCookie('pmaAuth-1', $this->cookieEncrypt($password, $blowfish_key), null, "/phpmyadmin/");
}
private function _useOpenSSL() {
return (function_exists('openssl_encrypt') && function_exists('openssl_decrypt') && function_exists('openssl_random_pseudo_bytes') && PHP_VERSION_ID >= 50304);
}
public function enlargeKey($key) {
while(strlen($key) < 16) {
$key .= $key;
}
return substr($key, 0, 16);
}
public function getMAC($key) {
$length = strlen($key);
if($length > 16) {
return substr($key, 0, 16);
}
return $this->enlargeKey($length == 1 ? $key : substr($key, 0, -1));
}
public function getAES($key) {
$length = strlen($key);
if($length > 16) {
return substr($key, 0, 16);
}
return $this->enlargeKey($length == 1 ? $key : substr($key, 0, -1));
}
public function cookieEncrypt($data, $key) {
$mac = $this->getMAC($key);
$aes = $this->getAES($key);
$iv = $this->createIV();
if($this->_useOpenSSL()) {
$result = openssl_encrypt(
$data,
'AES-128-CBC',
$key,
0,
$iv
);
} else {
$cipher = new Crypt\AES(Crypt\Base::MODE_CBC);
$cipher->setIV($iv);
$cipher->setKey($aes);
$result = base64_encode($cipher->encrypt($data));
}
$iv = base64_encode($iv);
return json_encode(
array(
'iv' => $iv,
'mac' => hash_hmac('sha1', $iv . $result, $mac),
'payload' => $result,
)
);
}
public function getIVSize() {
if($this->_useOpenSSL()) {
return openssl_cipher_iv_length('AES-128-CBC');
}
$cipher = new Crypt\AES(Crypt\Base::MODE_CBC);
return $cipher->block_size;
}
public function createIV() {
if(!is_null($this->_cookie_iv)) {
return $this->_cookie_iv;
}
if($this->_useOpenSSL()) {
return openssl_random_pseudo_bytes($this->getIVSize());
} else {
return Crypt\Random::string($this->getIVSize());
}
}
public function setIV($vector) {
$this->_cookie_iv = $vector;
}
}
Thanks for taking the time to read my problem and I hope someone can point me in the right direction.
This sounds exactly like what the auth_type signon was designed to address. Is there a particular reason you're not using that?
Failing that, the documentation shows how you can pass the username and password as part of the query string, which may not be ideal from a security standpoint, but might give you a starting place to make your modifications.
Have you tried POSTing the proper username and password directly to index.php? I'm not certain whether this will work because of the security token, but it's worth a try.
I feel really dumb now. Using signon session you have to declare the session variable for phpMyAdmin in your config. I was apparently unaware of this and upon changing this session variable I was able to single sign on users.
If you want to use the Signon authentication mode using signon.php as documented in examples folder do not forget to change the auth_type in config.inc.php
Change
$cfg['Servers'][$i]['auth_type'] = 'cookie';
To
$cfg['Servers'][$i]['auth_type'] = 'signon';
Also add the following
$cfg['Servers'][$i]['SignonSession'] = 'SignonSession';
$cfg['Servers'][$i]['SignonURL'] = 'examples/signon.php';

Clear cookies in yii2 after function call

I am facing some issues regarding clearing cookies in yii2. When i am calling a logout function on button click i am trying to perform following actions:
Set authtoken, and its expiration value to null
if Step got performed then clear session and cookies
but the problem is after setting the authtoken and its expiration value to null control is not going under if block (Where i am clearing session and cookies).
public function actionLogout()
{
$userId = \Yii::$app->user->identity->id;
$restobj = new RestController();
$this->token = NuLL;
$expire = Null;
$data = ['userId'=>$userId,'token'=>$this->token,'expire'=>$expire];
$data = json_encode($data);
$authtoken = $restobj->updateItem(\app\urls\urls::setauthtoken, $data);
if($authtoken)
{
$session = new Session();
$session->close();
$session->destroy();
$cookies = \Yii::$app->response->cookies;
unset($cookies['user_cookies']);
Yii::$app->user->logout();
return $this->goHome();
}
}
updateItem function is calling this authtoken function:
<?php
namespace app\actions\userloginactions;
use Yii;
use yii\rest\ActiveController;
use app\models\Authmaster;
use yii\base\Action;
class AuthtokenAction extends Action
{
//function used in rest api call for user token
public function run()
{
$data = Yii::$app->getRequest()->getBodyParams();
$userId = $data['userId'];
$token = $data['token'];
$expire = $data['expire'];
$result = Authmaster::setauthtoken($userId,$token,$expire);
return true;
}
}
setauthtoken function in model called from AuthtokenAction
public static function setauthtoken($userId,$token,$expire)
{
return Authmaster::updateAll(['token'=>$token,'expire'=>$expire],['user_id'=>$userId]);
}
when i click logout button it successfully sets the authtoken and expiration to null but it directly displays true as a result of AuthtokenAction function and control doesn't goes under if block.
that function call is creating some problem if i comment that and write cookies clearing block directly then cookies gets cleared without any problem.
Please check following code to clear all cookies. It is working for me, hope will work for you too.
Yii::$app->cache->flush()
Please try to use following line
$cookies = Yii::$app->response->cookies;
$cookies->remove('user_cookies');
Can you try this one?
if (isset($_SERVER['HTTP_COOKIE'])) {
$cookies = explode(';', $_SERVER['HTTP_COOKIE']);
foreach($cookies as $cookie) {
$parts = explode('=', $cookie);
$name = trim($parts[0]);
setcookie($name, '', time()-1000);
setcookie($name, '', time()-1000, '/');
}
}
Hope this helps others...
$cookies = Yii::$app->response->cookies;
$cookies->remove('username');
unset($cookies['username']);
Found in the following referenced link: http://www.bsourcecode.com/yiiframework2/cookies-handling-in-yii-framework2-0/

Converting from MD5 Legacy Auth System to CakePHP

I have a site which runs off an MD5 hashing scheme for passwords. As a way of supporting this legacy system, I've this answer to manually override the login system for now. But this isn't really ideal, as MD5 is pretty much universally known to be awful at encryption. So in the interest of security, what's the best way to migrate users over to the safer CakePHP auth system without causing them undue grief?
Figured it out thanks to this answer (albeit lightly modified). Basically, it updates the user behind the scenes to use the new system if the current system doesn't match up with it.
/**
* Login method
*/
public function login() {
$this->layout = 'homepage';
// If the user is already logged in, redirect to their user page
if($this->Auth->user() != null) {
$this->redirect();
} else {
// If this is being POSTed, check for login information
if($this->request->is('post')) {
if($this->Auth->login($this->loginHelper($this->request->data))) {
// Redirect to origin path, ideally
} else {
$this->Session->setFlash('Invalid username or password, try again');
}
}
}
}
/**
* Update password method
* #param array The user's data array
* #param Returns either a user object if the user is valid or null otherwise
*/
private function loginHelper($data) {
$username = $this->data['User']['username'];
$plainText = $this->data['User']['password'];
$user = current($this->User->findByUsername($username));
$salted = Security::hash($plainText, null, true);
if ($salted === $user['password']) {
return $user; // user exists, password is correct
}
$md5ed = Security::hash($plainText, 'md5', null);
if ($md5ed === $user['password']) {
$this->User->id = $user['id'];
$this->User->saveField('password', $plainText);
return $user; // user exists, password now updated to blowfish
}
return null; // user's password does not exist.
}

PHP session_regenerate_id (true) Not working as it should

EDIT: 4
I went and tried this out with teh regular session handler, same issue could it be some OS error?
session_start();
$_SESSION['h0']=5;
session_regenerate_id(true);
Again when reloading the page multiple times you get A LOT sessions all with the same data.
For some reason when executing this script the
define('endl', "<br>");
$session->start_session();
echo session_id().endl;
session_regenerate_id(true);
echo session_id().endl;
On the top part I'm using delete_old_session
session_regenerate_id(true)
bool session_regenerate_id ([ bool $delete_old_session = false ] )
So the expected behavior is to generate a new session and then delete the old one
if I execute it normally I have the right behavior...
output:
d5ips18ji4rg7q63skuf7955b4
udk903d5o2nbeoq5soujng0bp5
http://s7.postimg.org/67dbyv3x7/image.png
But if I reload the page multiple times, (keep f5 pressed for a couple o seconds...)
it created over 60 sessions
http://s7.postimg.org/442wr744b/image.png
I dont know if Im implementing this correctly...
EDIT 2:
Destroy callback
public function destroy($sessionId) {
$qry = "DELETE FROM sessions WHERE id = :id";
if (!isset($this->dStatement)) {
$this->dStatement = $this->pdo->prepare($qry);
}
$this->dStatement->bindParam(':id', $sessionId, PDO::PARAM_INT);
if ($this->dStatement->execute()) {
return true;
} else {
echo "error destroy()";
return false;
}
}
I've even tryied this methods insted of the regular sess_reg_id(true)
public function regen_id(){
$sessionId = session_id();
echo $sessionId;
$qry = "INSERT INTO sessiondeletequeue VALUES (:id, 0)";
if(!isset($this->regQuery)){
$this->regQuery = $this->pdo->prepare($qry);
}
$this->regQuery->bindParam(':id', $sessionId, PDO::PARAM_STR);
if($this->regQuery->execute()){
session_regenerate_id();
echo "<br>";
$this->forceDelete();
return true;
}
else{
return false;
}
}
private function forceDelete(){
$qry = "SELECT id FROM sessiondeletequeue";
foreach($this->pdo->query($qry) as $row){
$this->destroy($row['id']);
if(!isset($this->forceQuery)){
$this->forceQuery = $this->pdo->prepare("UPDATE sessiondeletequeue SET deleted = 1 WHERE id = :id");
}
$this->forceQuery->bindParam(':id', $row['id'], PDO::PARAM_STR);
$this->forceQuery->execute();
}
$this->pdo->query("DELETE FROM sessiondeletequeue WHERE deleted = 1 ");
EDIT 3:
I know I could find a way around it, but I'm curious to know why the heck is creating that many sessions!! D:
You're probably mixing up PHP's default session mechanism with your framework's or your own session implementation.
$session->start_session(); // where does $session come from?
//and then
session_id();
Yes, it's working the expected way. You're generating a new session ID on every page reload. So the newly generated session ID is being stored on the database.
Regenerate the session ID only when you need. You probably don't need it generated on every request to the page.

Categories