login script using sessions

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

method_man
Forum Contributor
Posts: 257
Joined: Sat Mar 19, 2005 1:38 am

login script using sessions

Post by method_man »

how would one go about making a login script using sessions that save to the database?
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

you've been here long enough to know how to search,

hint: session_set_save_handler()
method_man
Forum Contributor
Posts: 257
Joined: Sat Mar 19, 2005 1:38 am

Post by method_man »

actually i ment how to use it in my login.php file
i already hav the session thing

Code: Select all

<?php
require "db.php";

// Returns current time as a number. Used for recording the
// last session access.

function getMicroTime()
{
	// microtime() returns the number of seconds since
	// 0:00:00 January 1, 1970 GMT as a microsecond part
	// and a second part. e.g.: 0.08344800 1000952237

	// Convert the two parts into an array
	$mtime = explode(" ", microtime());

	// Return the addition of the two parts e.g.: 1000952237.08344800
	return($mtime[1] + $mtime[0]);
}

// The database connection
$connection = NULL;

// The global variable that holds the table name
$session_table= NULL;

// The session open handler called by PHP whenever
// a session is initialized. Always returns true.

function sessionOpen($database_name, $table_name)
{
	// Save the database connection in a global variable
	global $session_table;

	// Database credentials
	global $hostName;
	global $username;
	global $password;

	if (!($connection @ mysql_connect($hostName, $username, $password)))
		showerror();

	if (!mysql_select_db($database_name, $connection))
		showerror();

	$session_table = $table_name;

	return true;
}

// This function is called whenever a session_start() call is
// made and reads the session variables associated with the session
// identified by the $sess_id parameter. Returns "" when a session
// is not found and the session variables as a serialized string
// when the session exists.

function sessionRead($sess_id)
{
	// Access the DBMS connection
	global $connection;

	// Access the sessions table
	global $session_table;

	// Formulate a query to find the session identified by $sess_id
	$search_query = "SELECT * FROM {$session_table}
					 WHERE session_id = '{$sess_id}':;
	
	// Execute the query
	if (!($result = @mysql_query($search_query, $connection)))
		showerror();

	if(mysql_num_rows($result) == 0)
		//No session found - return the serialized string
		return "";
	  else
	{
		  //Found a session - return the serialized string
		  $row = mysql_fetch_array($result);
		  return $row["session_variable"];
	}
}

function sessionWrite($sess_id, $val)
{
	// Access the DBMS connection
	global $connection;

	// Access the sessions table
	global $session_table;

	$time_stamp = getMicroTime();

	$search_query = "SELECT session_id FROM {$session_table}
	WHERE session_id = '{sess_id}'";

	// Execute the query
	if (!($result - @ mysql_query($search_query, $connection)))
		showerror();

	if(mysql_num_rows($result) == 0)
	{
		// No session found, insert a new one
		$insert_query = "INSERT INTO {$session_table}
		(session_id, session_variable, last_accessed)
			VALUES ('{$sess_id)', '{$val}', {$time_stamp})";

		if (!mysql_query($insert_query, $connection))
			showerror();
	}
	else
	{
		// Existing session found - Update the session variables
		$update_query = "UPDATE {$session_table}
		SET session_variable = '{$val}',
			last_accessed = {$time_stamp}
		WHERE session_id = '{$sess_id}'";

		if(!mysql_query($update_query, $connection))
			showerror();
	}
}

// This function is executed on shutdown of the session.
// Always returns true.

function sessionClose()
{
	return true;
}

// This is called whenever the session_destroy() function
// call is made. Returns true if the session has successfully
// been deleted.

function sessionDestroy($sess_id)
{
	//Access the DBMS connection
	global $connection;

	// Access the sessions table
	global $sessions_table;

	$delete_query = "DELETE FROM {$session_table}
	WHERE session_id = '{$sess_id}'";

	if (!($result = @ mysql_query($delete_query, $connection)))
		showerror();

	return true;
}

// This function is called on a session's start up with the
// probability specified in session.gc_probability. Performs
// garbage collection by removing all sessions that haven't been
// updated in the last $max_lifetime seconds as set in
// session.gc_maxlifetime.
// Returns true if the DELETE query succeeded.

function sessionGC($max_lifetime)
{
	// Access the DBMS connection
	global $connection;

	//Access the sessions table
	global $session_table;

	$current_time = getMicroTime();

	$delete_query = "DELETE FROM {$session_table}
	WHERE last_accessed < ({$current_time} - {$max_lifetime})";

	if (!($result = @ mysql_query($delete_query, $connection)))
		showerror();

	return true;
}

// Call to register user call back functions.

session_set_save_handler("sessionOpen",
			 "sessionClose",
			 "sessionRead",
			 "sessionWrite",
			 "sessionDestroy",
			 "sessionGC");
?>
but how can i use this in a login script so if the user enters their username and password correctly then it logs them in?
method_man
Forum Contributor
Posts: 257
Joined: Sat Mar 19, 2005 1:38 am

Post by method_man »

anyone got an answer?
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

First of all, fix your parse error.
method_man
Forum Contributor
Posts: 257
Joined: Sat Mar 19, 2005 1:38 am

Post by method_man »

your talking about the colin here right?

Code: Select all

WHERE session_id = '{$sess_id}':;
method_man
Forum Contributor
Posts: 257
Joined: Sat Mar 19, 2005 1:38 am

Post by method_man »

so now i have this as my code

Code: Select all

<?php
require "dblink.php";

// Returns current time as a number. Used for recording the
// last session access.

function getMicroTime()
{
	// microtime() returns the number of seconds since
	// 0:00:00 January 1, 1970 GMT as a microsecond part
	// and a second part. e.g.: 0.08344800 1000952237

	// Convert the two parts into an array
	$mtime = explode(" ", microtime());

	// Return the addition of the two parts e.g.: 1000952237.08344800
	return($mtime[1] + $mtime[0]);
}

// The database connection
$connection = NULL;

// The global variable that holds the table name
$session_table= NULL;

// The session open handler called by PHP whenever
// a session is initialized. Always returns true.

function sessionOpen($database_name, $table_name)
{
	// Save the database connection in a global variable
	global $session_table;

	// Database credentials
	global $hostName;
	global $username;
	global $password;

	if (!($connection @ mysql_connect($hostName, $username, $password)))
		showerror();

	if (!mysql_select_db($database_name, $connection))
		showerror();

	$session_table = $table_name;

	return true;
}

// This function is called whenever a session_start() call is
// made and reads the session variables associated with the session
// identified by the $sess_id parameter. Returns "" when a session
// is not found and the session variables as a serialized string
// when the session exists.

function sessionRead($sess_id)
{
	// Access the DBMS connection
	global $connection;

	// Access the sessions table
	global $session_table;

	// Formulate a query to find the session identified by $sess_id
	$search_query = "SELECT * FROM {$session_table}
					 WHERE session_id = '{$sess_id}';
	
	// Execute the query
	if (!($result = @mysql_query($search_query, $connection)))
		showerror();

	if(mysql_num_rows($result) == 0)
		//No session found - return the serialized string
		return "";
	  else
	{
		  //Found a session - return the serialized string
		  $row = mysql_fetch_array($result);
		  return $row["session_variable"];
	}
}

function sessionWrite($sess_id, $val)
{
	// Access the DBMS connection
	global $connection;

	// Access the sessions table
	global $session_table;

	$time_stamp = getMicroTime();

	$search_query = "SELECT session_id FROM {$session_table}
	WHERE session_id = '{sess_id}'";

	// Execute the query
	if (!($result - @ mysql_query($search_query, $connection)))
		showerror();

	if(mysql_num_rows($result) == 0)
	{
		// No session found, insert a new one
		$insert_query = "INSERT INTO {$session_table}
		(session_id, session_variable, last_accessed)
			VALUES ('{$sess_id)', '{$val}', {$time_stamp})";

		if (!mysql_query($insert_query, $connection))
			showerror();
	}
	else
	{
		// Existing session found - Update the session variables
		$update_query = "UPDATE {$session_table}
		SET session_variable = '{$val}',
			last_accessed = {$time_stamp}
		WHERE session_id = '{$sess_id}'";

		if(!mysql_query($update_query, $connection))
			showerror();
	}
}

// This function is executed on shutdown of the session.
// Always returns true.

function sessionClose()
{
	return true;
}

// This is called whenever the session_destroy() function
// call is made. Returns true if the session has successfully
// been deleted.

function sessionDestroy($sess_id)
{
	//Access the DBMS connection
	global $connection;

	// Access the sessions table
	global $sessions_table;

	$delete_query = "DELETE FROM {$session_table}
	WHERE session_id = '{$sess_id}'";

	if (!($result = @ mysql_query($delete_query, $connection)))
		showerror();

	return true;
}

// This function is called on a session's start up with the
// probability specified in session.gc_probability. Performs
// garbage collection by removing all sessions that haven't been
// updated in the last $max_lifetime seconds as set in
// session.gc_maxlifetime.
// Returns true if the DELETE query succeeded.

function sessionGC($max_lifetime)
{
	// Access the DBMS connection
	global $connection;

	//Access the sessions table
	global $session_table;

	$current_time = getMicroTime();

	$delete_query = "DELETE FROM {$session_table}
	WHERE last_accessed < ({$current_time} - {$max_lifetime})";

	if (!($result = @ mysql_query($delete_query, $connection)))
		showerror();

	return true;
}

// Call to register user call back functions.

session_set_save_handler("sessionOpen",
			 "sessionClose",
			 "sessionRead",
			 "sessionWrite",
			 "sessionDestroy",
			 "sessionGC");
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

i was refering to

Code: Select all

$search_query = "SELECT * FROM {$session_table} WHERE session_id = '{$sess_id}';
to

Code: Select all

$search_query = "SELECT * FROM {$session_table} WHERE session_id = '{$sess_id}'";
Secondly, you should really understand what the class does before trying to use it. The only reason I raise this issue is because you want to integrate this into a login script, which does not need a session handler. Of course, it is your perogative if you choose to use this, but it useless using a snipplet you got off php.net and not completely understanding the benefits and such. A login script generally only requires to use a few session calls and using the internal session calls seems much more appropriate. Let me know if you still want to proceed.
method_man
Forum Contributor
Posts: 257
Joined: Sat Mar 19, 2005 1:38 am

Post by method_man »

um i think ill do it your way using a few session calls. how would i do it that way?

p.s. its from a book :D not php.net
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

This is assuming your form variables have already been send to the authentication script.

Code: Select all

$query = sprintf(&quote;SELECT * FROM `users` WHERE `user`='%s' AND `password`='%s' LIMIT 1&quote;,
			   mysql_real_escape_string($_POST&#1111;'user']),
			   mysql_real_escape_string($_POST&#1111;'password']));
			   
	$result = mysql_query($query) or die(mysql_error());
	
	if (mysql_num_rows($result) == 1) {
		$user = mysql_fetch_assoc($result);
		$_SESSION&#1111;'user'] = $user&#1111;'user'];
		$_SESSION&#1111;'id'] = $user&#1111;'id'];
		$_SESSION&#1111;'access'] = $user&#1111;'access'];
		$_SESSION&#1111;'logged'] = true;
		header('Location: private.php');
	}
	
	echo 'Login failed';
and then on pages you only want users who've logged in to be able to have access

Code: Select all

if ($_SESSION&#1111;'loggedin']) {
		echo 'You\'ve reached a private page!. You Must be logged in!';	
	}

This is the most basic it can get, I suggest you look at other examples on this board to see how they handle this. Better yet, expand on this snipplet.
method_man
Forum Contributor
Posts: 257
Joined: Sat Mar 19, 2005 1:38 am

Post by method_man »

ill try it and post back
thanks

[edit]

do i hav to $connect above the $query?
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

No you don't. If you execute a query it assumes the last made connection. If you are connecting to 1 database you don't have to define it within the query.
mysql_query() wrote:link_identifier
The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If by chance no connection is found or established, an E_WARNING level warning is generated.
method_man
Forum Contributor
Posts: 257
Joined: Sat Mar 19, 2005 1:38 am

Post by method_man »

it says its got a parse error and i cant find it
it says its in here

Code: Select all

$query = sprintf("SELECT * FROM `users` WHERE `username`='%s' AND `password`='%s' LIMIT 1",
               mysql_real_escape_string($_POST['username']),
               mysql_real_escape_string($_POST['password']));
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

huh? Show the error, I don't see any parse errors.
method_man
Forum Contributor
Posts: 257
Joined: Sat Mar 19, 2005 1:38 am

Post by method_man »

this is the error
Parse error: parse error in /home/www/twarowsk.freeownhost.com/StreetLife/login.php on line 8
this is my code

Code: Select all

<?php
 $connection = mysql_connect('127.0.0.1', 'root@localhost', '');
$mysql_select_db('streetlife');
if (!$connection){
   die('Could not connect);
}
echo "Connected successfully";

$query = sprintf("SELECT * FROM `users` WHERE `username`='%s' AND `password`='%s' LIMIT 1",
               mysql_real_escape_string($_POST['username']),
               mysql_real_escape_string($_POST['password']));
               
    $result = mysql_query($query) or die(mysql_error());
    
    if (mysql_num_rows($result) == 1) {
        $user = mysql_fetch_assoc($result);
        $_SESSION['user'] = $username['username'];
        $_SESSION['id'] = $username['id'];
        $_SESSION['access'] = $username['access'];
        $_SESSION['loggedin'] = true;
        header('Location: private.php');
    }
    
    echo 'Login failed';
?>
yes i did use $connect because for some reason it wouldnt connect without it
but anyways it says its on that line i think unless i cant count

btw... do i have to say what table to get username and password from or does it automaticaly find it in the streetlife database?
Post Reply