Board index   FAQ   Search  
Register  Login
Board index PHP PHP General

How to automatically detects active user? php

General discussions related to php

Moderators: macek, egami, gesf

How to automatically detects active user? php

Postby jhoiemarie » Fri Oct 19, 2012 12:31 am

I have been dying to ask this. How to keep user's session active that when he opens the same website in a new tab, it detects the current user and logs him automatically? Or when the the same user accidentally closed the browser tab, when he opened the same web site he still the active user, and he does not need to pass through the login page again? please help. thanks.
New php-forum User
New php-forum User
Posts: 1
Joined: Mon Dec 05, 2011 4:51 pm

Re: How to automatically detects active user? php

Postby seandisanti » Fri Oct 19, 2012 8:44 am

use cookies, here's some code from a recent project i was working on.
Code: Select all
//this function is called on my login page once credentials have been verified.
private function login_success($record)//$record holds user record from database
      if (isset($_POST['mem']))//this is a 'remember me' checkbox.
      { //wants to be remembered
         setcookie('pw',$record['password'],time()+3600*24*30);//this is a salted hashed password
         setcookie('id',$_SESSION['uid'], time()+3600*24*30);//and a unique id that the person never sees
      redirect_to('dashboard.php');//and then go to dashboard

I've added comments to help explain it a little better hopefully. Then you also have to have code on your login page to look for the cookie to bypass the login. I actually have a user object for the user, and when you go to a page, if you don't have session variables set from a successful login, it checks for cookies and processes login accordingly
Code: Select all
 class User {
   function __construct()
      if (! empty($_SESSION['email'])){redirect_to('dashboard.php');}
      if (isset($_COOKIE['id']) && isset($_COOKIE['pw'])) // has login cookie
         $salt = substr($_COOKIE['pw'],32);
         $arecord = self::find_by_id($_COOKIE['id']);
         if ($_COOKIE['pw']===$arecord['password']) //successful
         } else {
      if (! isset($record['email'])){
      } else {
php-forum Fan User
php-forum Fan User
Posts: 838
Joined: Mon Oct 01, 2012 12:32 pm

Return to PHP General

Who is online

Users browsing this forum: No registered users and 1 guest

Sponsored by Sitebuilder Web hosting and Traduzioni Italiano Rumeno and antispam for cPanel.