Session Id from mysql db

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
paramedicbob
Forum Newbie
Posts: 1
Joined: Sun Sep 18, 2011 2:54 pm

Session Id from mysql db

Post by paramedicbob »

I am trying to find out how to make my php site only show certen information to logged in users for example.

A department adds all of thier employees to the database.

I only want each department to be able to view and edit thier own employees.

What I am thinking is to use a session to grab the dept ID from the database. But I am unsure how to use a session this way or if a session wont work then what should I use?
User avatar
twinedev
Forum Regular
Posts: 984
Joined: Tue Sep 28, 2010 11:41 am
Location: Columbus, Ohio

Re: Session Id from mysql db

Post by twinedev »

Here is a sample way of doing it.

It assumes that you login via login.php which calls login-process.php which is below (see notes in code for how to handle errors on login.php)
Also assumed is that the page you are taken to when logged in by default is welcome.php and that this page is where you are taken to if you try to go to a page that is for a different department that you are not part of (see notes in code for how to handle it)

How it works:

You login, assuming you are logged in properly, it saves your login information to the session, including DeptID and the timestamp that you logged into the system to $_SESSION['Login']

The timestamp is saved so that it will force it to go back and recheck permissions every so often (in case admin disabled them or something). Adjust the time LOGIN_CHECK to what you feel is appropriate for your needs, set to 0 to force it to always check.

If you go to a page and you are not logged in (ie, you bookmarked it), it will save the current request to SESSION, and kick you to login, then once you login, instead of taking you to the welcome page, it will redirect you back to where you came from.

Lastly, if you just need them logged in, and don't care what department, on that page set DEPT_ID = 0 to indicate any department.

There are many ways to implement this, this is just one way that I came up with.

NOTE: for this example, i used MD5, but you should incorporate a stronger hash and salt / pepper to it as well (search here for "sha salt pepper" and you will find several threads on this)

login-process.php

Code: Select all

<?php

	if (isset($_SESSION['Login'])) {
		// This was being called as an include from a page to recheck login after certain time
		$strUser = $_SESSION['Login']['User'];
		$strPass = $_SESSION['Login']['Password'];
		$bIncluded = TRUE;
	}
	elseif (count($_POST)>0) {
		// This was called from the login form
		session_start(); // Always needs to be before any output to browser

		$bIncluded = FALSE;

		if (count($_POST)>0) {
			if (!isset($_POST['user']) || $_POST['user']='' || !isset($_POST['password']) || $_POST['password']=='') {
				// on login.php if $_GET['error'] = 1 display error like "Both Username and Password are required"
				header('Location: login.php?error=1');
				exit;
			}
			$strUser = $_POST['user'];
			$strPass = md5($_POST['password'];
		}
	}
	else {
		// This was directly called, kick to login page
		header('Location: login.php');
		exit;
	}

	require_once('database_connection.php');

	// Clear this value in case we kick back for login not working now
	if (isset($_SESSION['Login'])) { unset($_SESSION['Login']); }

	// NOTE: for simplicity sake, this example uses MD5, but you should use something stronger,
	//       perferably combined with a SALT and PEPPER value for the user

	$SQL  = 'SELECT `UserID`,`Status`,`DepartmentID` FROM `tblUser` ';
	$SQL .= 'WHERE `User`="'.mysql_real_escape_string($strUser).'" ';
	$SQL .= '  AND `Password`="'.md5($strPass).'" LIMIT 1';
	$rsUser = mysql_query($SQL);
	if (!$rsUser && mysql_num_rows($rsUser)==0) {
		// on login.php if $_GET['error'] = 3 display error like "Invalid user or password"
		header('Location: login.php?error=3');
		exit;
	}

	$aryUser = mysql_fetch_assoc($rsUser);
	mysql_free_result($rsUser);

	if ($aryUser['Status']!='Active') {
		// on login.php if $_GET['error'] = 2 display error like "User is disabled"
		header('Location: login.php?error=2');
		exit;
	}

	// Ok, we have a good user, continue on...

	$_SESSION['Login'] = array('UserID'=>$aryUser['UserID'],
	                           'User'=>$_POST['user'], 
	                           'Password'=>md5($_POST['password']),
	                           'DeptID'=>$aryUser['DepartmentID'],
	                           'Checked'=>time()); 

	if (!$bIncluded) {														 
		// This was a call from the login page, so redirect to new location
		if (isset($_SESION['CameFrom'])) {
			// They hit a page requiring login, so take them back there now they are logged in
			$strGoto = $_SESION['CameFrom'];
			unset($_SESSION['CameFrom']);
		}
		else {
			// They came from normal login page, so take them to inial user page
			$strGoto = 'welcome.php';
		}
		
		header('Location: '.$strGoto);
		exit;
	}
	// ELSE: This was included so we continue on our way....

// EOF: login-process.php
Sample of the top of any protected page

Code: Select all

<?php
	session_start(); // Always needs to be before any output to browser

	define('DEPT_ID',23); // SET THE DEPT ID NEEDED FOR THIS PAGE  0 = Any Department
	define('LOGIN_CHECK', 54000); // How often to check valid login against DB (54000 = 15 minutes)

	if (!isset($_SESSION['Login'])) {
		// Not logged in at all
		$_SESION['CameFrom'] = $_SERVER['REQUEST_URI']; // set so we come back here after loggin in
		header('Location: login.php');
		exit;
	}

	if ($_SESSION['Login']['Checked'] < (time()-LOGIN_CHECK)) {
		// It has been longer than 15 minutes since we last checked DB, so recheck in case they were disabled
		require_once('login-process.php'); 
	}

	// Check to make sure that they are in right department if it was set
	if (DEPT_ID>0 && $_SESSION['Login']['DeptID']!=DEPT_ID) {
		// on welcome.php if $_GET['error'] = 1 display error like "You are not in correct department to view that page"
		header('Location: welcome.php?error=1');
		exit;
	}

	// OK, continue with regular page as they are logged in and of a correct Dept ID

	// if you need DB access, make sure you use the following, as it may have already been included onnce already

	require_once('database_connection.php');

Post Reply