Php Session Timeout Secure - php

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

Related

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 login system suddenly stopped working

I built a PHP/MySql login system for a website I am working on and all was working fine. I took a month off from working on it, pulled it up last night, and all of a sudden it doesn't work. It recognizes if a wrong username or password was entered, but if you enter the correct information it redirects you to the login page again. Was there some update somewhere that I am unaware of? I did not change anything in any of my files. It was working perfectly a month ago, and with no change at all it doesn't work now. Any ideas?
UPDATE
It is working if I check the remember me box, but not if I don't I will paste my code below:
Login Script:
<?php
define('INCLUDE_CHECK',true);
require 'connect.php';
require 'functions.php';
session_name('TheLoginSession');
session_start();
// ---------- LOGIN ----------
if($_POST['submit']=='Login')
{
// Checking whether the Login form has been submitted
$err = array();
// Will hold our errors
if(!$_POST['username'] || !$_POST['password'])
$err[] = 'All the fields must be filled in!';
if(!count($err))
{
$_POST['username'] = mysql_real_escape_string($_POST['username']);
$_POST['password'] = mysql_real_escape_string($_POST['password']);
$_POST['remembercheck'] = (int)$_POST['remembercheck'];
$storedsaltquery = mysql_fetch_assoc(mysql_query("SELECT rand FROM members WHERE usr = '".$_POST['username']."'"));
$storedsalt = $storedsaltquery['rand'];
// Escaping all input data
$row = mysql_fetch_assoc(mysql_query("SELECT id,compid,usr,firstName,level,yn FROM members WHERE usr='{$_POST['usernamelog']}' AND pass='".hash("sha256",$_POST['passwordlog'].$storedsalt)."'"));
if($row['id'])
{
// If everything is OK login
$_SESSION['usr']=$row['usr'];
$_SESSION['comp']=$row['compid'];
$_SESSION['id'] = $row['id'];
$_SESSION['name'] = $row['firstName'];
$_SESSION['usrlevel'] = $row['level'];
$_SESSION['new'] = $row['yn'];
$_SESSION['remembercheck'] = $_POST['remembercheck'];
// Store some data in the session
setcookie('Remember','remembercheck',time()+1209600,'/','.domain.com');
}
else $err[]='Wrong username and/or password!';
}
if($err)
$_SESSION['msg']['login-err'] = implode('<br />',$err);
// Save the error messages in the session
echo header("Location: ../index.php");
exit;
}
Index Page:
<?php
define('INCLUDE_CHECK',true);
require 'includes/connect.php';
require 'includes/functions.php';
// Those two files can be included only if INCLUDE_CHECK is defined
session_name('TheLoginSession');
// Starting the session
session_start();
if($_SESSION['id'] && !isset($_COOKIE['Remember']) && !$_SESSION['remembercheck'])
{
// If you are logged in, but you don't have the Remember cookie (browser restart)
// and you have not checked the remembercheck checkbox:
$_SESSION = array();
session_destroy();
// Destroy the session
}
if(isset($_GET['logoff']))
{
$_SESSION = array();
session_destroy();
header("Location: index.php");
exit;
}
if($_SESSION['id'] && $_SESSION['new'] != 1){
header("Location: home.php");
exit;
}
?>
How can there be an update if nothing's changed?
Are you using a CMS or framework?
If it's all your own code, and you haven't changed anything, then nothing would have updated.
I've had an issue like this before but without more information, hard to know if it is the same issue. Mine had the symptom you describe (login with bad creds and get the authentication error, login with good creds and redirect back to login).
Mine was due to failing to include code to remove old session cookies. The login attempt 'works' but an old cookie also read and attempts to authenticate, fails (because it is too old), and kicks the user back to login.
If this is your issue, clear your site cookies and see if you can then log in.
If that works, you'll want to add some cleanup code to your logout and stale session handling. For instance, for logging out:
// per http://www.php.net/manual/en/function.session-destroy.php
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
session_destroy();
Again, just guessing at your issue here.

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();

PHP Login Code not Setting Permanent Cookie (Through Browser Close)

I'm using a PHP/MySQL Login Code, and I want it to store the cookie permanently (through browser closes), however it doesn't work. It logs in fine, and will remember up to a browser close, but forgets it afterwards. How can I fix this?
This is all the important code I think;
<?php
define('INCLUDE_CHECK',true);
require 'connect.php';
require 'functions.php';
// Those two files can be included only if INCLUDE_CHECK is defined
session_name('tzLogin');
// Starting the session
session_set_cookie_params(1000000*7*24*60*60);
session_start();
if($_SESSION['id'] && !isset($_COOKIE['tzRemember']) && !$_SESSION['rememberMe'])
{
// If you are logged in, but you don't have the tzRemember cookie (browser restart)
// and you have not checked the rememberMe checkbox:
$_SESSION = array();
session_destroy();
// Destroy the session
}
if(isset($_GET['logoff']))
{
$_SESSION = array();
session_destroy();
header("Location: index.php");
exit;
}
if($_POST['submit']=='Login')
{
// Checking whether the Login form has been submitted
$err = array();
// Will hold our errors
if(!$_POST['username'] || !$_POST['password'])
$err[] = 'All the fields must be filled in!';
if(!count($err))
{
$_POST['username'] = mysql_real_escape_string($_POST['username']);
$_POST['password'] = mysql_real_escape_string($_POST['password']);
$_POST['rememberMe'] = (int)$_POST['rememberMe'];
// Escaping all input data
$row = mysql_fetch_assoc(mysql_query("SELECT id,usr FROM tz_members WHERE usr='{$_POST['username']}' AND pass='".md5($_POST['password'])."'"));
if($row['usr'])
{
// If everything is OK login
$_SESSION['usr']=$row['usr'];
$_SESSION['id'] = $row['id'];
$_SESSION['rememberMe'] = $_POST['rememberMe'];
// Store some data in the session
setcookie('tzRemember',$_POST['rememberMe']);
// We create the tzRemember cookie
}
else $err[]='Wrong username and/or password!';
}
if($err)
$_SESSION['msg']['login-err'] = implode('<br />',$err);
// Save the error messages in the session
header("Location: nowloggedin.php");
exit;
}
?>
You need to set the expire time for the cookie:
setcookie('tzRemember',$_POST['rememberMe'], time()+3600);
That will make it last for one hour for example. If you don't set a time, it'll expire when the session is ended.
I've just noticed that you are setting the lifetime with session_set_cookie_params - as others have said, you're setting that way too far into the future.
It's best to stay below this year...
2038
Otherwise there will be issues and your browser will not store it.
You are setting the cookie as:
session_set_cookie_params(1000000*7*24*60*60);
Which sets the cookie to expire in 1000000*7*24*60*60 = 7*1000000/365 = 19000+ years. As far as I know, UNIX timestamp is not set for that long duration.

Need help in login code of php?

This is my code for login. when i try to login at 1st time it pass blank value to session.but when i go back to login page again & signin that time it successfully signin.
i didnt understand whats wrong with this code?? plz help me.
session_unset();
session_start();
Global $i;
$root = $_SERVER['DOCUMENT_ROOT'];
include($root."/signinConfig.php");
function redirect($redirect=null)
{
header("Location : $redirect");
}
if (isset($_POST['submit']))
{
$check = mysql_query("SELECT * FROM user_reg WHERE `username` = '".$_POST['username']."'")or die("Dont Dare To Hack");
$check2 = mysql_numrows($check);
if ($check2 == 0)
{
die('That user does not exist in our database. Click Here To Register');
}
else
{
$i=0;
$password = mysql_result($check,$i,"password");
$_POST['pass'] = stripslashes($_POST['pass']);
$pass = md5($_POST['pass']);
if ($pass == $password)
{
$_SESSION['username']= mysql_result($check,$i,"username");
mysql_close();
redirect("/User_CP/user_cp.php");
}
else
{
die('Incorrect password, please try again.');
}
}
}//after this html code take place
in config file i store database connection code & session expire code. here it is
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1000)) { // last request was more than 30 minates ago
session_destroy(); // destroy session data in storage
session_unset(); // unset $_SESSION variable for the runtime
}
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
Ok first of all, your redirect function is missing exit(); after header
function redirect($redirect=null)
{
header("Location : $redirect");
exit();
}
The problem is that if you dont give exit, the code will continue running after the redirect function.
for example, here you have
redirect("/User_CP/user_cp.php");
And it will redirect the page, but the php will still be running and if you have a session_destroy() or session_unset() function after that line it will be executed and the session will get expire.
It is also possible that even if the session is not being destroyed it might be causing some conflicts.
Try that exit() and let me know.

Categories