Keep users logged in for 9hours until click logout - php

I am facing an issue with my script in Godaddy shared hosting. users gets logged out randomly,
can someone help fix my code to keep users logged in for at least 9hours without losing session once logged in?
i have tried numerous ways like increasing the session.gc.lifetime through php.ini and also htaccess but still users are getting logout out randomly.
here is my login execution php code
include('password.php');
class User extends Password{
private $_db;
function __construct($db){
parent::__construct();
$this->_db = $db;
}
private function get_user_hash($username){
try {
$stmt = $this->_db->prepare('SELECT member_id, employee_id, password, username, level, team FROM crm_members WHERE username = :username ');
$stmt->execute(array('username' => $username));
return $stmt->fetch();
} catch(PDOException $e) {
echo '<p class="bg-danger">'.$e->getMessage().'</p>';
}
}
public function login($username,$password){
$row = $this->get_user_hash($username);
if($this->password_verify($password,$row['password']) == 1){
$_SESSION['crm_loggedIn'] = true;
$_SESSION['crm_member_id'] = $row['member_id'];
$_SESSION['crm_employee_id'] = $row['employee_id'];
$_SESSION['crm_username'] = $row['username'];
$_SESSION['crm_level'] = $row['level'];
$_SESSION['crm_team'] = $row['team'];
return true;
}
}
public function crm_logout(){
session_destroy();
}
public function is_logged_in(){
if(isset($_SESSION['crm_loggedIn']) && $_SESSION['crm_loggedIn'] == true){
return true;
}
}
}
and this bit of code i put in every pages for check if user is logged in
if(!$user->is_logged_in()){ header('Location: login.php'); }
and this is for logout.php
$user->crm_logout();
Will really be thankful if you could help me out with my above codes.
Thanks in advance

See if the below helps.
In your PHP add the following;
<?php
// Server Keeps session for 32400 seconds which is actually 9 hours. That is 3600 x 9
ini_set('session.gc_maxlifetime', 32400);
// Client remembers session for 32400 seconds which is actually 9 hours. That is 3600 x 9
session_set_cookie_params(32400);
?>
See this documentation here for your reference https://www.codeleaks.io/increase-session-timeout-in-php/

Related

Automatically log out php application after 2 mins

I have finished designing an application but would like to make the application logout out after 5 minutes of inactivity.
The first page is:
<?php
session_start();
require_once("class.user.php");
$login = new USER();
if($login->is_loggedin()!="")
{
$login->redirect('user.php');
}
?>
This is the user page:
<?php
require_once("session.php");
require_once("class.user.php");
$auth_user = new USER();
$user_pin = $_SESSION['user_session']; ?>
The session.php page
<?php
session_start();
require_once 'class.user.php';
$session = new USER();
if(!$session->is_loggedin())
{
$session->redirect('index.php');
}
?>
This are the classes:
require_once('dbconfig.php');
class USER
{
private $conn;
public function __construct()
{
$database = new Database();
$db = $database->dbConnection();
$this->conn = $db;
}
public function runQuery($sql)
{
$stmt = $this->conn->prepare($sql);
return $stmt;
}
public function is_loggedin()
{
if(isset($_SESSION['user_session']) )
{
return true;
}
}
public function redirect($url)
{
header("Location: $url");
}
public function doLogout()
{
session_destroy();
unset($_SESSION['user_session']);
return true;
}
}
?>
Theres multiple ways to achieve this:
You can make a verification with a cookie or a session with a Timestamp to verify if the user has not changed paged within 2 minutes and it will log him out the moment he access that page. The Con in this method is that for all intents and purposes the user is still considered "Online" until he changes page.
My preferred method is to make a pooling with JQuery and Ajax request.
Basically every X seconds you send a request with AJAX to the user to see if hes still there and update his timestamp on the database. And then with a server side script if the timestamp has reach 2 minutes difference set the user offline and force log him out.
There is always websockets, at the moment im exploring this method with rachetphp but it allows you to track a connection in real time, which is also pretty sweet.
Check this link for methods.

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.

Session: Everyone in the internet is logged in when a user logs in

I have used sessions before but this is weird. I have created a login page and I am using sessions. I am using the following function to check whether a person is logged in:
function check_login() {
if(isset($_SESSION['user_id'])){
$this->user_id = $_SESSION['user_id'];
$this->logged_in = true;
} else {
unset($this->user_id);
$this->logged_in = false;
}
}
However, when the first user logs in, everyone on the internet can access the restricted page with the details of the logged in person. What could I be doing wrong? How should I differentiate the users?
Thanks in advance.

PHP login issue when moving to a different server

I have a very basic log in system, which I have tested on my localhost as well as a free hosting site I use to test my projects and all worked fine.
I have just moved the site to Site Ground as a subdomain and the login has stopped working. The site is still loading content from the database I have created in this location, so I know the issue is not a result from a failure to connect to the database.
There is nothing in the .htaccess file to block a user login either, if it is an issue with moving it to a new server, how would I find a way around this? The page does NOT return any error when attempting to login
login PHP:
<?php
require 'includes/connect.php';
session_start();
if(isset($_POST['login'])){
$username = $_POST['username'];
$password = md5 ($_POST['password']);
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT COUNT(user_id) FROM nathan WHERE username='$username' AND password='$password'";
$q = $pdo->prepare($sql);
$q->execute();
$count = $q->fetchColumn();
if($count == 1){
$_SESSION['username'] = $username;
header('Location: admin.php');
}
}
?>
DB connection:
<?php
class Database
{
private static $dbName = "some_DB" ;
private static $dbHost = "localhost" ;
private static $username = "some_user";
private static $password = "password123";
private static $cont = null;
public function __construct() {
die('Init function is not allowed');
}
public static function connect()
{
// One connection through whole application
if ( null == self::$cont )
{
try
{
self::$cont = new PDO( "mysql:host=".self::$dbHost.";"."dbname=".self::$dbName, self::$username, self::$password);
}
catch(PDOException $e)
{
die($e->getMessage());
}
}
return self::$cont;
}
public static function disconnect()
{
self::$cont = null;
}
}
?>
Session PHP:
<?php
session_start();
if (!isset($_SESSION['username'])){
header('Location: login.php');
};
?>
You might want to inspect your cookies when viewing and verify that you indeed are getting a cookie set with session information. If this isn't working, my limited view of your environment would suggest that you're not allowing cookies from that specific subdomain.
Another thing to check is the directory where sessions data is stored. If that isn't populated, then you're not going to be able to persist a session.
As the poster above me said it is definitely because of the cookies, refer to this post for solutions PHP Sessions across sub domains
And you shouldn't store password directly in the database, it is insecure, you should hash it with password_hash(), and then compare it with hash_equals(), on login.

Session lost for user login

I ask for help to you, I explain my problem. In my User () class, I wrote a small function to log in, then recording sessions and setting cookies.
Here it is:
public function login($username, $password) {
$this->db->query("SELECT * FROM users WHERE username = :username AND status = :status LIMIT 1");
$this->db->bind(':username', $username);
$this->db->bind(':status', 1);
$row = $this->db->single();
$count = $this->db->rowCount();
if ($count > 0) {
if (password_verify($password, $row['password'])) {
$this->setSession($row);
return true;
} else {
return false;
}
}
}
public function setSession($row) {
$_SESSION['session'] = [
'id' => $row['id'],
'username' => $row['username'],
'email' => $row['email']
];
//set cookie
setcookie("name_cookie", md5($_SESSION['session']['username']/$_SESSION['session']['password']), time()+3600 * 24 * 365);
}
And here is the function to check if the user is connected or not, to protect the pages:
public function isLoggedIn() {
if(isset($_SESSION['session'])) {
return true;
}
return false;
}
My problem would be that even if cookies are set, unfortunately the session after a total time expires.
I set the cookies to a year, but as I said, the user's login session expires after a while. How can I correct this?
PHP sessions expire at the server level. The default is around 20 minutes, and you can control this in your php.ini settings.
You could use setcookie to save a cookie to the user's browser, and then check it using the $_COOKIE variable in PHP. See setcookie.
But be aware of the security risks with this. Anyone can steal the cookie and then get access to the site as that user. Some good ideas for securing your cookie can be found here.

Categories