How to automatically detects active user? php

General discussions related to php

Moderators: egami, macek, gesf

Post Reply
seandisanti
php-forum Fan User
php-forum Fan User
Posts: 973
Joined: Mon Oct 01, 2012 12:32 pm

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
	{
		$_SESSION['uid']=$record['id'];
		$_SESSION['firstName']=$record['first_name'];
		$_SESSION['lastName']=$record['last_name'];
		$_SESSION['email']=$record['email'];
		$_SESSION['user_type_id']=$record['user_type_id'];
		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
			{
			self::login_success($arecord);
			} else {
			setcookie('id',$_COOKIE['id'],1);
			redirect_to('login.php?cookiefail=1');
			}
		}
		$record=self::login($_POST['un'],$_POST['pw']);
		if (! isset($record['email'])){
			redirect_to("login.php?fail=1");
		} else {
		self::login_success($record);
		}
	}

Post Reply
  • Information
  • Who is online

    Users browsing this forum: No registered users and 1 guest