Problem with remember me button on mobile devices - php

I have made easy login system according to one article on web. If I click remember me button it stores these data (member_login, random_password, random_selector) in cookies on device, where I am logged in. First I used it just on PC.
Later I added IP address verificaction step to enable login on more devĂ­ces in same time due to I want to use my app also on mobile device.
Login system is working correctly on PC - there I can be logged in one month if I choose remember me during login.
On mobile devices, on every browser it randomly log out me after some random period.
I already checked if cookies are created on mobile and it is ok.
I could not find rootcause why. Can you please advice me what to check.
Here is my login code, where cookies are setted up:
<?php
require_once ($_SERVER['DOCUMENT_ROOT'] . '/_inc/functions.php');
require_once ($_SERVER['DOCUMENT_ROOT'] . '/_inc/auth/Util.php');
require_once ($_SERVER['DOCUMENT_ROOT'] . '/_inc/auth/Auth.php');
$auth = new Auth();
$db_handle = new DBController();
$util = new Util();
// Get Current date, time
$current_time = time();
$current_date = date("Y-m-d H:i:s", $current_time);
// Set Cookie expiration for 1 month (seconds from 1970 until current date + 1 month)
$cookie_expiration_time = $current_time + (30 * 24 * 60 * 60); // for 1 month
// Auth.php chcek if user is loggedin
if ($_SESSION["user_id"]) {
redirect_page("index.php");
exit;
}
// check if login form was submitted
if (! empty($_POST['login'])) {
$isAuthenticated = false;
// get username and password from form
$username = $_POST['username'];
$password = $_POST['password'];
// get user from db
$user = $auth->getMemberByUsername($username);
// verify entered password with hashed password in db for user got above
if (password_verify($password, $user[0]["password"])) {
$isAuthenticated = true; // password is verified, next rocess of login can start
}
// if user is authenticated start to create cookies
if ($isAuthenticated) {
$_SESSION["user_id"] = $user[0]["id"];
// Set Auth Cookies if 'Remember Me' checked
if (! empty($_POST["remember"])) {
$ip_address = $_SERVER['REMOTE_ADDR'];
// setcookie(string $name, string $value = "", int $expires = 0,)
setcookie("member_login", $username, $cookie_expiration_time, '/'); // '/' cookies are available on each page
$random_password = $util->getToken(16); // create token for cookie identification with db
setcookie("random_password", $random_password, $cookie_expiration_time, '/'); // '/' cookies are available on each page
$random_selector = $util->getToken(32);
setcookie("random_selector", $random_selector, $cookie_expiration_time, '/'); // '/' cookies are available on each page
// hash password and selector before inserting to db
$random_password_hash = password_hash($random_password, PASSWORD_DEFAULT);
$random_selector_hash = password_hash($random_selector, PASSWORD_DEFAULT);
$expiry_date = date("Y-m-d H:i:s", $cookie_expiration_time);
// mark existing token as expired if new login
$userToken = $auth->getTokenByUsername($username, 0);
/*
if (! empty($userToken[0]["id"])) {
$auth->markAsExpired($userToken[0]["id"]);
}
*/
// Insert new token
$auth->insertToken($username, $ip_address, $random_password_hash, $random_selector_hash, $expiry_date);
} else {
$util->clearAuthCookie();
}
redirect_page("index.php");
exit;
} else {
$_SESSION['login_error'] = 'Invalid password or username';
redirect_page("back");
exit();
}
}
Hrere is my validation code to check cookies on each page:
<?php
/* FLow:
-> index -> header -> validatecookies ()
-> continue index (logedin = true)
-> redirect login
*/
require 'Util.php';
require 'Auth.php';
// create objects
$auth = new Auth();
$db_handle = new DBController();
$util = new Util();
$isLoggedIn = false;
// Check if loggedin session and redirect if session exists
if (! empty($_SESSION["user_id"])) {
$isLoggedIn = true;
}
// Check if loggedin cookies exists
else if (! empty($_COOKIE["member_login"]) && ! empty($_COOKIE["random_password"]) && ! empty($_COOKIE["random_selector"])) {
// Initiate auth token verification directive to false
$isPasswordVerified = false;
$isSelectorVerified = false;
$isExpiryDateVerified = false;
// Get token for username from db
$userToken = $auth->getTokenByIPaddress($_SERVER['REMOTE_ADDR'],0);
// $userToken = $auth->getTokenByUsername($_COOKIE["member_login"],0);
if ($userToken) {
// check just in case of the same IP address
// dual control via selector and password due to time leake secure issue (if just one token than according to response time from db it is possible to guess password easier)
// Validate random password cookie with database
if (password_verify($_COOKIE["random_password"], $userToken[0]["password_hash"])) {
$isPasswordVerified = true;
}
// Validate random selector cookie with database
if (password_verify($_COOKIE["random_selector"], $userToken[0]["selector_hash"])) {
$isSelectorVerified = true;
}
// check cookie expiration by date
if( ($userToken[0]["expiry_date"] >= $current_date) & ($userToken[0]["is_expired"] != 1) ) {
$isExpiryDateVerified = true;
}
}
// Redirect if all cookie based validation returns true
// Else, mark the token as expired and clear cookies
if (!empty($userToken[0]["id"]) && $isPasswordVerified && $isSelectorVerified && $isExpiryDateVerified) {
$isLoggedIn = true;
} else {
if(!empty($userToken[0]["id"])) {
$auth->markAsExpired($userToken[0]["id"]);
}
// clear cookies
$util->clearAuthCookie();
header ("Location: login.php");
exit;
}
} else {
// is no session and no cookies exist, just redirect on login
header ("Location: login.php");
exit;
}
?>
``

Related

Don't allow new user, if a user has already logged in

error_log('my test');
if(isset($_SESSION["userName"])){
// some user is present CHECK AND ALLOW THE LOGIN.
// Another user has already logged in. so check if the last session activity is more than the SESSIONTIMEOUT value.
$idleTime = (time() - $_SESSION['LAST_ACTIVE_TIME'])/60;
$idleTime=9;$sessionTimeOut=10;
if($idleTime<$sessionTimeOut) {
print("*****1*****");
$existingUser=$_SESSION["userName"];
// IDLE TIME IS LESSTHAN THE SESSIONTIMEOUT SO ONLY ALLOW IF IT IS AN OLD USER
if(strcasecmp( $existingUser, $name ) == 0){
print("*****2*****");
$_SESSION["userName"] = $name;
$_SESSION["ipaddr"] = $ipaddr;
$_SESSION["type"] = $type;
$_SESSION['LAST_ACTIVE_TIME'] = time();
updateUserInfo($name,$ipaddr,$type);
$url ="./PHome.php" ;
// header("Location: $url");
} else {
print("*****3*****");
// IDLE TIME IS LESSTHAN THE SESSIONTIMEOUT AND new user, SO don't allow
$url ="./Login.html" ;
//header("Location: $url?error=duplicateErr");
}
} else {
print("*****4*****");
// IDLE TIME IS MORE than sessionTimeOut, SO NEW SECOND USER HAS LOGGED IN
$_SESSION["userName"] = $name;
$_SESSION["ipaddr"] = $ipaddr;
$_SESSION["type"] = $type;
$_SESSION['LAST_ACTIVE_TIME'] = time();
updateUserInfo($name,$ipaddr,$type);
$url ="./PHome.php" ;
// header("Location: $url");
}
} else {
print("*****0*****");
error_log("errors occured");
// No user is present So Log in
$_SESSION["userName"] = $name;
$_SESSION["ipaddr"] = $ipaddr;
$_SESSION["type"] = $type;
$_SESSION['LAST_ACTIVE_TIME'] = time();
updateUserInfo($name,$ipaddr,$type);
$url ="./PHome.php" ;
//header("Location: $url");
}
// Logic,
First I am checking if the user has already logged in, if not I am allowing the user to Login,
Now if a second user comes since the session is already set it should not allow the user to login, But this is allowing.
Test Scenario - Login using Chrome first and then using an IE, a second user is able to log in.
I Can't use a database, as the db is getting locked and the whole application dies.
Any help is highly appreciated.
Though I'm not sure if you are trying, to stop a same "user" from "same ip" to login is different, but if you want to stop multiple logins in same user this can be the technique
Add a field in DB beside the user
On login turn it to 1 (You should keep an inactivity timer though to make it 0 after some hours/minutes)
While login just add a statement to check if that field is 0 or 1

Using session variables on other pages

This question might be a bit stupid but I am only starting my adventure with sessions - didn't need to use them before. On the homepage I have a session which stores all the variables properly, that's no problem.
When I go to a sub-page under the same domain and try to call the variables from session, I just get empty fields. I tried doing print_r($_REQUEST); on the sub-page and it prints out the following:
Array ( [wp-settings-1] => libraryContent=browse&editor=html [wp-settings-time-1] => 1478015951 [PHPSESSID] => 0744bf21ab3712e4735e07d926433aa3 [sec_session_id] => 60e56049f51c76e9ec4932c6702e7b72 )
Which matches the output on the homepage. I know I should do a session_start(); but when I include that in my code I get the following error:
Notice: A session had already been started - ignoring session_start()
The reason I know that the variables are not being passed is because when I do
if(isset($_SESSION["user_id"])){
$user_id = $_SESSION["user_id"];
}
echo "User id: " .$_SESSION["user_id"];
I only get
User id:
And whenever I try to call the variable I get an error that it is not set.
Is there a step that I am missing?
Setting the session variables:
if ($stmt->num_rows == 1) {
// If the user exists we check if the account is locked
// from too many login attempts
if (checkbrute($user_id, $mysqli) == true) {
// Account is locked
// Send an email to user saying their account is locked
return false;
} else {
// Check if the password in the database matches
// the password the user submitted.
if ($db_password == $password) {
// Password is correct!
// Get the user-agent string of the user.
$user_browser = $_SERVER['HTTP_USER_AGENT'];
// XSS protection as we might print this value
$user_id = preg_replace("/[^0-9]+/", "", $user_id);
$_SESSION['user_id'] = $user_id;
$sessions['user_id'] = $user_id;
// XSS protection as we might print this value
$username = preg_replace("/[^a-zA-Z0-9_\-]+/", "", $username);
$_SESSION['username'] = $username;
$_SESSION['login_string'] = hash('sha512', $password . $user_browser);
// Login successful.
return true;
} else {
// Password is not correct
// We record this attempt in the database
$now = time();
if (!$mysqli->query("INSERT INTO login_attempts(user_id, time)
VALUES ('$user_id', '$now')")) {
header("Location: ../error.php?err=Database error: login_attempts");
exit();
}
return false;
}
}
} else {
// No user exists.
return false;
And the function to start secure session:
function sec_session_start() {
$session_name = 'sec_session_id'; // Set a custom session name
$secure = SECURE;
// This stops JavaScript being able to access the session id.
$httponly = true;
// Forces sessions to only use cookies.
if (ini_set('session.use_only_cookies', 1) === FALSE) {
header("Location: ../error.php?err=Could not initiate a safe session (ini_set)");
exit();
}
// Gets current cookies params.
$cookieParams = session_get_cookie_params();
session_set_cookie_params($cookieParams["lifetime"], $cookieParams["path"], $cookieParams["domain"], $secure, $httponly);
// Sets the session name to the one set above.
session_name($session_name);
session_start(); // Start the PHP session
session_regenerate_id(); // regenerated the session, delete the old one.
}
By seeing you code i understand it is wordpress site,
if yes follow following steps:
step1: add following code into your wp-content/themes-folder/functions.php
add_action('init', 'myStartSession', 1);
add_action('wp_logout', 'myEndSession');
add_action('wp_login', 'myEndSession');
function myStartSession() {
if(!session_id()) {
session_start();
}
}
function myEndSession() {
session_destroy ();
}
step 2: set user_id
$_SESSION['user_id'] = "your id";
step 3: to access your session id
if(isset($_SESSION['user_id'])) {
$value = $_SESSION['myKey'];
} else {
$value = '';
}
if your site is not a wordpress
add session_start() at header.php(or first line of your code)
then use your session variables.

Login script, cookie saved wrong pass?

I have this easy to use login for my page wich i have been using a long time.
Now im trying to modify it abit so that my username and password is stored in a database instead of in clear text in the file.
The password is stored with MD5 in the database and the login works fine, but when i enter a site where you have to be logged in i get re-directed into the login screen where it says wrong password...
what am i doing wrong?
<?php
$un = $_POST['user'];
require_once ('/inc/login_conn.php');
$dsn = "mysql:Server=$Lhost:$Lport;Database=$Ldb";
$sql = "SELECT * FROM Users WHERE UserName= '$un'";
$stmt = $conn->prepare($sql);
$stmt->execute ();
$sett1= $stmt->fetch(PDO::FETCH_ASSOC);
$user = $sett1['UserName'];
$pass = $sett1['Password'];
define('LOGIN_USER', "$user");
//define('LOGIN_USER', "USERNAME");
define('LOGIN_PASS', "$pass");
//define('LOGIN_PASS', "PASSWORD");
class Login {
// unique prefix that is used with this object (on cookies and password salt)
var $prefix = "login_";
// days "remember me" cookies will remain
var $cookie_duration = 1;
var $user = "";
var $pass = "";
function authorize() {
//save cookie info to session
if(isset($_COOKIE[$this->prefix.'user'])){
$_SESSION[$this->prefix.'user'] = $_COOKIE[$this->prefix.'user'];
$_SESSION[$this->prefix.'pass'] = $_COOKIE[$this->prefix.'pass'];
}
// else{echo "no cookie<br>";}
//if setting vars
if(isset($_POST['action']) && $_POST['action'] == "set_login"){
$this->user = $_POST['user'];
$this->pass = md5($this->prefix.md5($_POST['pass'])); //hash password. salt with prefix
$this->check();//dies if incorrect
//if "remember me" set cookie
if(isset($_POST['remember'])){
setcookie($this->prefix."user", $this->user, time()+($this->cookie_duration*86400));// (d*24h*60m*60s)
setcookie($this->prefix."pass", $this->pass, time()+($this->cookie_duration*86400));// (d*24h*60m*60s)
}
//set session
$_SESSION[$this->prefix.'user'] = $this->user;
$_SESSION[$this->prefix.'pass'] = $this->pass;
}
//if forced log in
elseif(isset($_GET['action']) && $_GET['action'] == "prompt"){
session_unset();
session_destroy();
//destroy any existing cookie by setting time in past
if(!empty($_COOKIE[$this->prefix.'user'])) setcookie($this->prefix."user", "blanked", time()-(3600*25));
if(!empty($_COOKIE[$this->prefix.'pass'])) setcookie($this->prefix."pass", "blanked", time()-(3600*25));
$this->prompt();
}
//if clearing the login
elseif(isset($_GET['action']) && $_GET['action'] == "clear_login"){
session_unset();
session_destroy();
//destroy any existing cookie by setting time in past
if(!empty($_COOKIE[$this->prefix.'user'])) setcookie($this->prefix."user", "blanked", time()-(3600*25));
if(!empty($_COOKIE[$this->prefix.'pass'])) setcookie($this->prefix."pass", "blanked", time()-(3600*25));
$msg = '<h2 class="msg">**Logout complete**</h2>';
$this->prompt($msg);
}
//prompt for
elseif(!isset($_SESSION[$this->prefix.'pass']) || !isset($_SESSION[$this->prefix.'user'])){
$this->prompt();
}
//check the pw
else{
$this->user = $_SESSION[$this->prefix.'user'];
$this->pass = $_SESSION[$this->prefix.'pass'];
$this->check();//dies if incorrect
}
}#-#authorize()
function check(){
if(md5($this->prefix . LOGIN_PASS) != $this->pass || LOGIN_USER != $this->user){
//destroy any existing cookie by setting time in past
if(!empty($_COOKIE[$this->prefix.'user'])) setcookie($this->prefix."user", "blanked", time()-(3600*25));
if(!empty($_COOKIE[$this->prefix.'pass'])) setcookie($this->prefix."pass", "blanked", time()-(3600*25));
session_unset();
session_destroy();
$msg='<h2 class="warn">Incorrect username or password</h2>';
$this->prompt($msg);
}
}#-#check()
function prompt($msg=''){
?>
Session:
<?php
session_start();
require("/Login.class.php");
$login = new Login;
$login->authorize();
?>
EDIT:
If i change the line
$this->pass = md5($this->prefix.md5($_POST['pass'])); //hash password. salt with prefix
To as it were before i tried to get my username and pw from db:
$this->pass = md5($this->prefix.$_POST['pass']); //hash password. salt with prefix
and log in with my hashed password, it still does not seem to work.... so might the problem be somewhere else? if i set define_user and define_pass to static vars it works like a charm...

PHP session not holding value on page change

I know there are quite a few posts about this topic but none of them have fixed my issue.
I have WAMP server running on my windows computer. I've created a login system that is able to set PHP sessions and verify that they are working while on the page that they were created. Once I change to a different page, either by typing in the URL or a javascript function I lose the session.
Here is my test.php that logs a user in
require_once('config.php');
$user = new User();
$result = $user->login('email#gmail.com', 'mysecretpassword');
echo $result;
echo '</br>';
$result = $user->isLoggedIn();
echo $result;
This is the function that actually logs the user in
public function login($email, $password) {
// Hash Password
$password = $this->hashPassword($password);
// Check if email and password match
$query = "SELECT id, confirm_email FROM users WHERE email = ? AND password = ?";
$a_bind_params = array($email, $password);
$a_param_types = array('s','s');
$results = $this->db->select($query, $a_bind_params, $a_param_types);
// If we didnt get a result then email/password must be wrong
if(count($results) == 0) return 1;
// Now check that they verrified their email
if($results[0]['confirm_email'] == 'N') return 2;
// User is real and everything is good
// Update login Date
$a_bind_params = array(date('Y-m-d H:i:s'), $results[0]['id']);
$a_param_types = array('s','s');
$query = "UPDATE users SET login_at = ? WHERE id = ?";
// There was a problem updating their login table so just fail the login
if(!$this->db->update($query, $a_bind_params, $a_param_types)) return 3;
// Login user
Session::set("user_id", $results[0]['id']);
session_regenerate_id(true);
Session::set("login_fingerprint", $this->_generateLoginString ());
return 0;
}
Here is the function that checks if the user is logged in
// Checks if user is logged in
public function isLoggedIn() {
//if $_SESSION['user_id'] is not set return false
if(Session::get("user_id") == null)
return false;
$loginString = $this->_generateLoginString();
$currentString = Session::get("login_fingerprint");
if($currentString != null && $currentString == $loginString)
return true;
else {
//destroy session, it is probably stolen by someone
$this->logout();
return false;
}
}
Here is the Session function that creates a session
public static function startSession() {
ini_set('session.use_only_cookies', true);
$cookieParams = session_get_cookie_params();
session_set_cookie_params(
$cookieParams["lifetime"],
$cookieParams["path"],
$cookieParams["domain"],
SESSION_SECURE,
SESSION_HTTP_ONLY
);
session_start();
session_regenerate_id(true);
}
These are the function that set/get the user session
public static function set($key, $value) {
$_SESSION[$key] = $value;
}
public static function get($key, $default = null) {
if(isset($_SESSION[$key]))
return $_SESSION[$key];
else
return $default;
}
Finally this is my config.php file that actually calls session_start() and include some constants
// REQUIRE ALL FILES
require_once("ClassSession.php");
require_once("ClassDatabase.php");
require_once("ClassUser.php");
Session::startSession();
If I navigate to another page called test.php
include "config.php";
$user = new User();
if($user->isLoggedIn()) echo 'logged in';
else 'Not logged in';
The session is lost and the user is not logged in anymore.
I've checked my sessions.save_path in PHP.ini and have checked the wamp64/temp folder and my sessions are being stored in there. I am also calling session_start() on every page because I am including config.php on both the test pages. Not sure why I am losing my sessions.
EDIT
I forgot to mention what is actually happening. When I login the user I look up their user_id from the database and store that into $_SESSION['user_id']. When I access $_SESSION[user_id] from the page that logged the user in I get back the correct value. However, when I change to another page $_SESSION['user_id'] is null.
UPDATE
session_regenerate_id(true) is not the problem.
Here are my Session settings when printing php_info()
session_set_cookie_params(
$cookieParams["lifetime"],
$cookieParams["path"],
$cookieParams["domain"],
SESSION_SECURE,
SESSION_HTTP_ONLY
);
Check values here. What is SESSION_SECURE const value? Maybe you are restricting cookie usage to https only and your site is on http.
I just wrote a very basic PHP code to give you an idea how this can be quickly built. You should change the parameters, use mysqli or PDO or ORM whichever you like but the basic idea remains the same. Use secure cookies, follow the best practices to hide what needs to be secured.
Create a php file call it functions.php and paste the following code in it
<?php
session_start();
function createsessions($email, $password, $loginId)
{
//Add additional member to Session array as per requirement
//session_register();
$_SESSION["email"] = $email;
$_SESSION["password"] = $password;
$_SESSION["loginId"] = $loginId;
//Add additional member to cookie array as per requirement
setcookie("loginEmail", $_SESSION['loginEmail'], time() + 31536000, "/", ".example.com", 0, true);
setcookie("password", $_SESSION['password'], time() + 31536000, "/", ".example.com", 0, true);
setcookie("loginId", $_SESSION['loginId'], time() + 31536000, "/", ".example.com", 0, true);
}
#Authenticate User
function confirmUser($email_address, $password)
{
if (mysql_num_rows(mysql_query("select * from TABLE where email ='" . $email_address . "' and password =MD5('" . $password . "')"))) {
$loginstatus = 1; //account exists, login
return $loginstatus;
} else {
$loginstatus = 0; // Incorrect Credentials
return $loginstatus;
}
}
#Function to check login status
function checkLoggedin()
{
if (isset($_SESSION['email']) && isset($_SESSION['password']))
return true;
elseif (isset($_COOKIE['email']) && isset($_COOKIE['password'])) {
if (confirmUser($_COOKIE['email'], $_COOKIE['password'])) {
$sql_id = mysql_query("select id, email, password from TABLE where email ='" . $_COOKIE['email'] . "' and password ='" . $_COOKIE['password'] . "'");
$sql_array = mysql_fetch_row($sql_id);
#Register Session & Cookies Variables
$loginId = $sql_array[0];
$email = $sql_array[1];
$password = $sql_array[2];
//Clear all sessions and cookies first
clearsessionscookies();
createsessions($email, $password, $loginId);
return true;
} else {
clearsessionscookies();
return false;
}
} else
return false;
}
#Logout and clear session and cookies data
function clearsessionscookies()
{
unset($_SESSION['email']);
unset($_SESSION['password']);
unset($_SESSION['loginId']);
setcookie("PHPSESSID", null, time() - 31536000, "/", ".example.com", 0);
setcookie("email", null, time() - 31536000, "/", ".example.com", 0);
setcookie("password", null, time() - 31536000, "/", ".example.com", 0);
setcookie("loginId", null, time() - 31536000, "/", ".example.com", 0);
session_unset();
session_destroy();
ob_end_flush();
}
?>
createsessions() and clearsessionscookies() helps in handling session creation and deletion. Replace example.com to your cookie domain.
From your HTML Page, make an AJAX Call to a function and put the following code in it
<?php
#AJAX Call to this function
function checkLogin()
{
// Don't forget to protect against MySQL injection
$user_email = mysql_real_escape_string($_POST['emailaddress']);
$password = mysql_real_escape_string($_POST['password']);
if ($user_email == '' || $password == '') {
echo "Invalid email address or password. Please try again.";
$hasError = true;
}
$loginstatus = confirmUser($user_email, $password);
if ($loginstatus == 0) {
echo "Invalid ID or password. Please try again.";
$hasError = true;
} else // Login Now
{
if ($hasError != true) {
#Get User Details In Session
$sql_id = mysql_query("select loginId, email, password from TABLE where email ='" . $user_email . "' and password =MD5('" . $password . "')");
$sql_array = mysql_fetch_row($sql_id);
#Register Session & Cookies Variables
$loginId = $sql_array[0];
$email = $sql_array[1];
$password = $sql_array[2];
//Create Fresh sessions and cookies
createsessions($email, $password, $loginId);
//Redirect to Dashboard or wherever you want the customer to go post authentication
}
}
}
?>
I have purposely kept the LoginID so you can specifically handle the particular record for referencing with other tables you might have associated with the user table.
I hope this will work and help you keep the user logged in for the specified period in the cookie.
Your problem could be
session_regenerate_id(true);
This is going to delete your session and update it with a new session id and you are going to lose the association with any session data for the old session id.
From the docs for the parameter to this function.
delete_old_session
Whether to delete the old associated session file or not.
You said config.php calls session_start(); however I see you are using
ini_set(use.cookie, true)
That is wrong and causing your issue.

Modifying the code I got from WikiHow's Secure Session Login script

I wanted to implement the secure login script from WikiHow in my project. I have got it working in CodeIgniter. I want to modify it a bit by logging out a user when he closes the browser (unless he checked Remember Me on the login page).
This is the login function (assume every variable is set because the function won't be called unless they are).
public function login() {
$error_msg = array();
// the email and password validation is here
// if error is found its pushed into the $error_msg array
// find the user corresponding to the given email address
$sql = "SELECT user_id, username, password, salt FROM users WHERE email = ? LIMIT 1";
$query = $this->db->query($sql, $email);
if ($query) {
if ($query->num_rows() == 1) {
$result = $query->row();
// user is found
// hash the pass with the salt
$password = hash('sha512', $password.$result->salt);
// check for number of tries
if ($this->check_brute($result->user_id) == TRUE) {
// account locked for repeated failed login attempts
$error_msg[] = "<p>Account is locked due to repeated failed login attempts.</p>";
// return FALSE;
} else {
// check password
if ($password == $result->password) {
$user_browser = $this->security->xss_clean($_SERVER['HTTP_USER_AGENT']); // browser
$user_id = preg_replace("/[^0-9]+/", "", $result->user_id);
$username = preg_replace("/[^a-zA-Z0-9_\-]+/", "", $result->username);
// i want to set the cookie expiry time depending on the
// remember me checkbox
if ($_POST['remember']) {
}
// i am guessing somekinda cookie manipulation should
// take place here
// assign session variables
$_SESSION['user_id'] = $user_id;
$_SESSION['username'] = $username;
$_SESSION['login_string'] = hash('sha512', $password.$user_browser);
return TRUE; // login success
} else {
// wrong password input
// add activity in database
$sql = "INSERT INTO login_attempts (user_id, time) VALUES (?, ?)";
$this->db->query($sql, array($result->user_id, time()));
$error_msg[] = "<p>ERR PASS: Username/password combination is incorrect.</p>";
// return FALSE;
}
}
} else {
// user doesnt exist
// return FALSE;
$error_msg[] = "<p>NO USR: Username/password combination is incorrect.</p>";
}
}
return $error_msg;
}
And this is the code for the session starting:
public function sec_session_start() {
$session_name = "sec_session_id";
$secure = FALSE; // dev mode
$httponly = TRUE;
if(ini_set('session.use_only_cookies', 1) === FALSE) {
$error_msg = '<p>Could not initiate a secure session.</p>';
return $error_msg;
}
$cookieParams = session_get_cookie_params();
session_set_cookie_params(
$cookieParams['lifetime'],
$cookieParams['path'],
$cookieParams['domain'],
$secure,
$httponly);
session_name($session_name);
session_start();
session_regenerate_id(TRUE);
return TRUE;
}
The only place where there is a reference to cookies is in the logout function where it is unset. What should I do to set the cookie expiry time when a user logs in depending on their choice on "Remember me"?
I had the same problem using this script and this is the solution that I came up with.
In your login function, add this code:
(I am assuming $_POST['remember'] will be = 1 if user wants to be remembered, 0 otherwise)
if ($_POST['remember']) {
$_SESSION['remember'] = $_POST['remember'];
}
Then in the function sec_session_start() add this after session_start():
...
session_name($session_name);
session_start();
if($_SESSION['remember'] == 1){ session_set_cookie_params(60*60*24*60); }
session_regenerate_id(true);
...
The lifetime can obviously be changed to suit you. I chose 2 months for this example.
What this code is effectively doing is setting another session which contains the information as to whether or not the user wants to remembered.
The cookie is then initially set with the default value that your server has set for session lifetimes, but if the remember session has a value of 1, it changes this to the lifetime you have set.
I've not extensively tested this so let me know if any issues arise.

Categories