PHP session not renewing - php

I have a logout script for my web app which is the following:
<?php
session_start();
require_once("config.php");
$logout_connect = mysql_connect($db_host, $db_user, $db_pass);
if (!$logout_connect){
die('Impossibile connettersi: ' . mysql_error());
}else{
mysql_select_db($db_name, $logout_connect);
mysql_query("DELETE FROM valutazioni_recenti WHERE idutente = '".$_SESSION['userid']."' ");
if(mysql_query("DELETE FROM sessions WHERE ssnid = '".$_SESSION['ssnid']."' AND userid = '".$_SESSION['userid']."'")){
$_SESSION = array();
$session_id = session_id();
session_destroy();
mysql_close($logout_connect);
header("location: login.php?logout");
exit();
}
}
?>
It makes me logout the user correctly, but, as I save session data in a DB on login and delete them on logout, I can see that if I login with a session id like "096c02aefbb34jd175bfa89d4ec1235" when I logout and login again it gives me the same sessionid to that specific user.
Is it normal? Is there a way to change it? Do I just have to mix it (or m5d it) with the login time??

you are missing something in your logout code that is your cookie values stored in user's browser . PHP function session_destroy(); doesn't delete user cookies, you have to unset them manually by setting expiry time to back date or time.
setcookie ("TestCookie", "", time() - 3600); //will set expiry time one hour back
so if you don't unset user's browser's cookie it will take same session id every time when you make new login.

This is completely normal, don't worry about it. Some other people asked about the same thing in StackOverflow.
This is due the cookies stored in your browser, so to "fix it" you must either delete the cookie either regenerate the ID with PHP.
You have a better explanation in a different post:
why is php generating the same session ids everytime in test environment (WAMP)?

Try this:
<?php
/* CREDITS: Sergio Abreu
* dosergio#gmail.com
*/
// Session Configuration
$minutes = 1 * 60; // One hour
$obsess = array();
if( $_SESSION ){
foreach ( $_SESSION as $k=>$v){
$obsess[$k] = $v;
}
session_destroy();
session_set_cookie_params( $minutes * 60);
}
ini_set( "session.use_cookies", 1);
ini_set( "session.gc_probability", 1);
ini_set( "session.gc_divisor", 1);
ini_set( "session.cookie_lifetime", $minutes * 60);
ini_set( "session.gc_maxlifetime", $minutes * 60);
//Starts new Session
session_start();
// Restore data:
if( $obsess ){
foreach ( $obsess as $k=>$v){
$_SESSION[$k] = $v;
}
}
?>

Related

Php Session Timeout Secure

I was wondering how to make php session timeout? i have this so far, Or make it so people can use cookie and login..
<?php
include('config.php');
session_start();
$user_check=$_SESSION['login_user'];
$ses_sql=mysql_query("select username from admin where username='$user_check' ");
$row=mysql_fetch_array($ses_sql);
$login_session=$row['username'];
if(!isset($login_session))
{
header("Location: login.php");
}
?>
Your code will never time out because $login_session will be set so long as the user still exists in the DB.
Store the expiration time in the session. Abstract the code below in a file that you include on every protected page.
<?php
if(session_status()===PHP_SESSION_NONE) session_start();
//if user supplied login creds:
if(isset($_POST['username']) && isset($_POST['password'])){
//attempt to login,
//...
// if login worked save username and expiration time
if(...){
$_SESSION['user'] = $row['username'];
$_SESSION['exp'] = time() + 600; //expires in 10 minutes
}
}
//now check access
if(empty($_SESSION['user'])){
//user is not logged in. show error and exit
}elseif(empty($_SESSION['exp']) || $_SESSION['exp'] < time()){
//session has expired. show error and exit
}
//session is still valid. Extend expiration:
$_SESSION['exp'] = time() + 600; //expires in 10 minutes
//show protected content

Can you help me add session timeout code to my login facility?

I am creating a small login facility. i would like it to be simple but also secure.
I wanted to timeout my session after 30 minutes of inactivity. I saw a solution for this here by Gumbo. However I am unsure where to add the code to my own code... Can somebody help me ...
Here is the solution which i want to add into my code (by Gumbo) and underneath that is my own login.php page:
Conclusion / best solution (from another stackoverflow post ):
The best solution is to implement a session timeout of your own. Use a simple time stamp that denotes the time of the last activity (i.e. request) and update it with every request:
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) {
// last request was more than 30 minutes ago
session_unset(); // unset $_SESSION variable for the run-time
session_destroy(); // destroy session data in storage
}
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
Updating the session data with every request also changes the session file's modification date so that the session is not removed by the garbage collector prematurely.
You can also use an additional time stamp to regenerate the session ID periodically to avoid attacks on sessions like session fixation:
if (!isset($_SESSION['CREATED'])) {
$_SESSION['CREATED'] = time();
} else if (time() - $_SESSION['CREATED'] > 1800) {
// session started more than 30 minutes ago
session_regenerate_id(true); // change session ID for the current session and invalidate old session ID
$_SESSION['CREATED'] = time(); // update creation time
}
login.php
<?php
session_start();
header('Content-Type: text/html; charset=utf-8');
require("database.php");
require("phpfunctions.php");
if(isset($_POST["log_out"]) && ($_POST["log_out"] == '1')) {
//this means we have come from another page after pressing the log out button
//so therefore we remove session variables and destroy session
session_unset();
session_destroy();
//$log_out_message = "You have been logged out";
}
if (isset($_SESSION["username"])) {
//if the username session variable is already set then they are already logged in so send them to the index page
//we will perform further checks there on the validity of the session variables
header("Location: index.php");
exit();
}
//collect the post data if the login form has been submitted
if (isset($_POST["username"]) && isset($_POST["password"])){
$username = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["username"]); // filter everything but numbers and letters
$password = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["password"]); // filter everything but numbers and letters
//check if this username and password exist in our database and are therefore valid
$query = "SELECT * FROM users WHERE username=:username LIMIT 1";
$statement = $pdoConnection->prepare($query);
$statement->bindValue(':username', $username, PDO::PARAM_STR);
$statement->execute();
$statement->setFetchMode(PDO::FETCH_ASSOC);
$count = 0;
while($row = $statement->fetch()){
//username exists.
if (password_verify($password, $row["hashedPassword"])) {
//password is verified
//store the hashedPassword into a variable.
$dbHashedValue = $row["hashedPassword"];
$id = $row["userID"];
$count++;
}
}
//if count is 1 that means we found matching username in our database and also have verifed the password
if($count == 1){
//If our login credentials are matched with the database and therefore valid we store the values into session variables.
//$_SESSION['incorrectLogin'] = false;
$_SESSION["userID"] = $id;
$_SESSION["username"] = $username;
$_SESSION["password"] = $dbHashedValue;
//all login information is correct and we have stored it into SESSION variables so
//we are ready to allow the user in to our system
header("Location: index.php");
//exit the rest of the script
exit();
}else if($count == 0){
//create generic message without giving too much information away to the user in order to be more secure.
$incorrectLoginDetails = "Invalid Login! Please try again!";
}
}
?>
index.php
<?php
session_start();
header('Content-Type: text/html; charset=utf-8');
require("database.php");
require("phpfunctions.php");
//check if the username session variable exists
//this will exist only if the person has passed the login stage therefore we now know they are logged in
if(!isset($_SESSION['username'])){
header('Location: login.php');
exit();
}
//also need to check this username exists in the database and also that the session password matches up with the database.
?>

PHP, MySQL - login\logout issue, login only after second attempt

I have a very strange logout issue.
The flow of the work:
Log in page
Main view (choosing a task)
Task initialization that prepares the task in the background
Task view (submitting some answer and clicking on submit)
updates in the DB. initialization of the next line (go to number 3)
I am using Session and cookies in order to login.
The problem occurs only one time after logout the user tries to login.
He succeffully reaches his Main view (different for each user)
Successfully choose a task, go to the task view, enters submit.
Then instead of the next page he receives "log out, please login" statement, meaning that my "checkUser" didnt find a session or a cookie and kicked him out.
When he makes the login the next time, everything is working correctly.
I dont understand where to begin to look for this issue.
My login page relevant code:
session_start();
$error_msg = "";
//Do you have Session or cookies?
if (isset($_SESSION['user_id']) && isset( $_SESSION['user_role']))
{
If ($_SESSION['user_role']=='DM')
header('Location: DMView.php');
else if ($_SESSION['user_role']=='Vendor')
header('Location: VendorView.php');
exit;
}
//If you dont - Did you enter sumbit?
if (!isset($_SESSION['user_id']) && isset($_POST['submit']))
{
// Grab the user-entered log-in data
$user_username = mysqli_real_escape_string($con, trim($_POST['username']));
$user_password = mysqli_real_escape_string($con, trim($_POST['password']));
if (!empty($user_username) && !empty($user_password)) {
// Look up the username and password in the database
$query = "SELECT * FROM Users WHERE UserName = '$user_username' AND UserPassword = SHA('$user_password')";
$data = mysqli_query($con, $query);
if (mysqli_num_rows($data) == 1) {
// The log-in is OK so set the user ID and username session vars (and cookies), and redirect to the home page
$row = mysqli_fetch_array($data);
$_SESSION['user_id'] = $row['UserID'];
$_SESSION['username'] = $row['UserName'];
setcookie('user_id', $row['UserID'], time() + (60 * 60 * 24 * 30)); // expires in 30 days
setcookie('username', $row['UserName'], time() + (60 * 60 * 24 * 30)); // expires in 30 days
$user_role = $row['UserRole'];
$_SESSION['user_role'] = $row['UserRole'];
setcookie('user_role', $row['UserRole'], time() + (60 * 60 * 24 * 30)); // expires in 30 days
$_SESSION['user_group'] = $row['UserGroup'];
setcookie('user_group', $row['UserGroup'], time() + (60 * 60 * 24 * 30)); // expires in 30 days
If ($user_role=='DM')
header('Location: DMView.php');
else
header('Location: VendorView.php');
}
else {
// The username/password are incorrect so set an error message
$error_msg = 'Sorry, you must enter a valid username and password to log in.';
}
}
else {
// The username/password weren't entered so set an error message
$error_msg = 'Sorry, you must enter your username and password to log in.';
}
}
My checkUser file:
if (session_status() == PHP_SESSION_NONE)
{
session_start();
}
// If the session vars aren't set, try to set them with a cookie
if (!isset($_SESSION['user_id'])) {
if (isset($_COOKIE['user_id']) && isset($_COOKIE['username'])) {
$_SESSION['user_id'] = $_COOKIE['user_id'];
$_SESSION['username'] = $_COOKIE['username'];
$_SESSION['user_role']=$_COOKIE['user_role'];
$_SESSION['user_group'] = $_COOKIE['user_group'];
}
}
if ((!isset($_SESSION['user_id'])) ) {
echo '<p>Please log in to access this page.</p>';
exit();}
and my Logout file:
// If the user is logged in, delete the session vars to log them out
session_start();
if (isset($_SESSION['user_id'])) {
// Delete the session vars by clearing the $_SESSION array
$_SESSION = array();
// Delete the session cookie by setting its expiration to an hour ago (3600)
if (isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', time() - 3600);
}
// Destroy the session
session_destroy();
}
// Delete the user ID and username cookies by setting their expirations to an hour ago (3600)
setcookie('user_id', '', time() - 3600);
setcookie('username', '', time() - 3600);
// Redirect to the home page
header('location: index.php');
The submit file (simplified with only one query):
<?php
require('connection.php');
require ('checkUser.php');
$task=$_POST['task_id'];
$row=$_POST['row_id'];
if( $_POST['answer']==1 )
{
$query="UPDATE ecnmatchingdetails SET RowStatus=2,Agent='".$uName."' , VendorAnswer='Yes', VendorComment='".$_POST['comments']."' , end_tag='".date("Y-m-d H:i:s")."' where TaskID=".$task." and RowId=".$row;
mysqli_query($con, $query);
}
else...
}
if( isset( $_POST['answer'])) {
header( 'Location: http://dub-entas-124/tool/TT/WorkOnTask.php?id='.$task . '&start_task=0&prevID='.$Ebay_PRD_ID);
exit();
}
?>
If I guess your question correct,
You are registering cookie and in same page you are checking, being cookie stored in client side, it will be available only after reload or on another page...
I had this issue for a while and looked everywhere.
All I did to fix this was change this in my php.ini
session.cookie_domain = ".example.com"
Put this before the session_start() which should be at the very top of your PHP
ini_set('session.cookie_domain', '.example.com' );
session_start();

Close session and start a new one

I'm testing the implementation of a security check in my PHP sessions. I can successfuly detect whether the session was started from another IP address and I can successfully start a new session. However, the data from the old session gets copied into the new one! How can I start a blank session while preserving the previous session data for its legitimate owner?
This is my code so far, after lots of failed attempts:
<?php
// Security check
if( isset($_SESSION['ip_address']) && $_SERVER['REMOTE_ADDR']!=$_SESSION['ip_address'] ){
// Check failed: we'll start a brand new session
session_regenerate_id(FALSE);
$tmp = session_id();
session_write_close();
unset($_SESSION);
session_id($tmp);
session_start();
}
// First time here
if( !isset($_SESSION['ip_address']) ){
$_SESSION['ip_address'] = $_SERVER['REMOTE_ADDR'];
$_SESSION['start_date'] = new DateTime;
}
The official documentation about sessions is terribly confusing :(
Update: I'm posting some findings I got through trial and error. They seem to work:
<?php
// Load the session that we will eventually discard
session_start();
// We can only generate a new ID from an open session
session_regenerate_id();
// We store the ID because it gets lost when closing the session
$tmp = session_id();
// Close session (doesn't destroy data: $_SESSION and file remains)
session_destroy();
// Set new ID for the next session
session_id($tmp);
unset($tmp);
// Start session (uses new ID, removes values from $_SESSION and loads the new ones if applicable)
session_start();
Just call session_unset after session_regenerate_id to reset $_SESSION for the current session:
if (isset($_SESSION['ip_address']) && $_SERVER['REMOTE_ADDR']!=$_SESSION['ip_address']) {
// Check failed: we'll start a brand new session
session_regenerate_id(FALSE);
session_unset();
}
when a new user connects to your server, the script should only be able to access that user's session variables. you will want to store other info in a hashed session variable to verify that the session is not being jacked. if it is being jacked, no reason to start a new session, maybe just exit the script with a warning.
here is the function a lot of people use for fingerprinting a session:
function fingerprint() {
$fingerprint = $server_secure_word;
$fingerprint .= $_SERVER['HTTP_USER_AGENT'];
$blocks = explode('.', $_SERVER['REMOTE_ADDR']);
for ($i=0; $i<$ip_blocks; $i++) {
$fingerprint .= $blocks[$i] . '.';
}
return md5($fingerprint);
}
Use this
unset($_SESSION['ip_address'])
instead of 'unset($_session)'
You can also use session_destroy.
session_destroy will destroy session data. For example,
session_start();
$_SESSION["test"] = "test";
session_write_close();
session_start();
// now session is write to the session file
// call session_destroy() will destroy all session data in the file.
session_destroy();
// However the you can still access to $_SESSION here
print_r($_SESSION);
// But once you start the session again
session_start();
// all session data is gone as the session file is now empty
print_r($_SESSION);
will output
array([test] => "test")array()

Login for PHP site sometimes works

I'm having a problem with my login system. Sometimes it works, sometimes it doesn't. It seems that it fails on the first try more often than not and works on the second go around. There is NO ERROR; the page redirects to the home page as it is supposed to but the session variables are coming up empty.
The first code block is the relevant login script after a username/pass was accepted. The second block is what i use to see if the user has any cookies if the the session vars arn't set the home page. The third clock is my logout script.
Thanks in advance.
// The log-in is OK so set the user ID and username session vars (and cookies), and redirect to the home page
$row = mysqli_fetch_array($data);
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['username'] = $row['username'];
$_SESSION['first_name'] = $row['first_name'];
if($rememberme == 1)
{
setcookie('user_id', $row['user_id'], time() + (60 * 60 * 24 * 30)); // expires in 30 days
setcookie('username', $row['username'], time() + (60 * 60 * 24 * 30)); // expires in 30 days
setcookie('first_name', $row['first_name'], time() + (60 * 60 * 24 * 30)); // expires in 30 days
}
if($ref==0)
{
header("location: http://domain.com/test.php");
}
else
{
header("location: http://domain.com/".$ref);
}
second block:
session_start();
if (!isset($_SESSION['user_id'])) {
if (isset($_COOKIE['user_id']) && isset($_COOKIE['username']) && isset($_COOKIE['first_name'])) {
$_SESSION['user_id'] = $_COOKIE['user_id'];
$_SESSION['username'] = $_COOKIE['username'];
$_SESSION['first_name'] = $_COOKIE['first_name'];
}
}
third block:
// If the user is logged in, delete the session vars to log them out
session_start();
if (isset($_SESSION['user_id']))
{
// Delete the session vars by clearing the $_SESSION array
$_SESSION = array();
// Delete the session cookie by setting its expiration to an hour ago (3600)
if (isset($_COOKIE[session_name()]))
{
setcookie(session_name(), '', time() - 3600);
}
// Destroy the session
session_destroy();
}
// Delete the user ID and username cookies by setting their expirations to an hour ago (3600)
setcookie('user_id', '', time() - 3600);
setcookie('username', '', time() - 3600);
// Redirect to the home page
header('Location: http://domain.com/test.php');
Try destroying your session variables in your log out script, also at the beginning of your log in script.

Categories