When one is lost, seek help...

When help is lost, refer to Open Source code that works (^_^)

This is how phpBB does their sessions in phpBB 2.0.23.

includes/sessions.php

<?php
/***************************************************************************
 *                                sessions.php
 *                            -------------------
 *   begin                : Saturday, Feb 13, 2001
 *   copyright            : (C) 2001 The phpBB Group
 *   email                : support@phpbb.com
 *
 *   $Id: sessions.php 5930 2006-05-18 19:23:07Z grahamje $
 *
 *
 ***************************************************************************/

/***************************************************************************
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 ***************************************************************************/

//
// Adds/updates a new session to the database for the given userid.
// Returns the new session ID on success.
//
function session_begin($user_id, $user_ip, $page_id, $auto_create = 0, $enable_autologin = 0, $admin = 0)
{
	global $db, $board_config;
	global $HTTP_COOKIE_VARS, $HTTP_GET_VARS, $SID;

	$cookiename = $board_config['cookie_name'];
	$cookiepath = $board_config['cookie_path'];
	$cookiedomain = $board_config['cookie_domain'];
	$cookiesecure = $board_config['cookie_secure'];

	if ( isset($HTTP_COOKIE_VARS[$cookiename . '_sid']) || isset($HTTP_COOKIE_VARS[$cookiename . '_data']) )
	{
		$session_id = isset($HTTP_COOKIE_VARS[$cookiename . '_sid']) ? $HTTP_COOKIE_VARS[$cookiename . '_sid'] : '';
		$sessiondata = isset($HTTP_COOKIE_VARS[$cookiename . '_data']) ? unserialize(stripslashes($HTTP_COOKIE_VARS[$cookiename . '_data'])) : array();
		$sessionmethod = SESSION_METHOD_COOKIE;
	}
	else
	{
		$sessiondata = array();
		$session_id = ( isset($HTTP_GET_VARS['sid']) ) ? $HTTP_GET_VARS['sid'] : '';
		$sessionmethod = SESSION_METHOD_GET;
	}

	//
	if (!preg_match('/^[A-Za-z0-9]*$/', $session_id)) 
	{
		$session_id = '';
	}

	$page_id = (int) $page_id;

	$last_visit = 0;
	$current_time = time();

	//
	// Are auto-logins allowed?
	// If allow_autologin is not set or is true then they are
	// (same behaviour as old 2.0.x session code)
	//
	if (isset($board_config['allow_autologin']) && !$board_config['allow_autologin'])
	{
		$enable_autologin = $sessiondata['autologinid'] = false;
	}

	// 
	// First off attempt to join with the autologin value if we have one
	// If not, just use the user_id value
	//
	$userdata = array();

	if ($user_id != ANONYMOUS)
	{
		if (isset($sessiondata['autologinid']) && (string) $sessiondata['autologinid'] != '' && $user_id)
		{
			$sql = 'SELECT u.* 
				FROM ' . USERS_TABLE . ' u, ' . SESSIONS_KEYS_TABLE . ' k
				WHERE u.user_id = ' . (int) $user_id . "
					AND u.user_active = 1
					AND k.user_id = u.user_id
					AND k.key_id = '" . md5($sessiondata['autologinid']) . "'";
			if (!($result = $db->sql_query($sql)))
			{
				message_die(CRITICAL_ERROR, 'Error doing DB query userdata row fetch', '', __LINE__, __FILE__, $sql);
			}

			$userdata = $db->sql_fetchrow($result);
			$db->sql_freeresult($result);
		
			$enable_autologin = $login = 1;
		}
		else if (!$auto_create)
		{
			$sessiondata['autologinid'] = '';
			$sessiondata['userid'] = $user_id;

			$sql = 'SELECT *
				FROM ' . USERS_TABLE . '
				WHERE user_id = ' . (int) $user_id . '
					AND user_active = 1';
			if (!($result = $db->sql_query($sql)))
			{
				message_die(CRITICAL_ERROR, 'Error doing DB query userdata row fetch', '', __LINE__, __FILE__, $sql);
			}

			$userdata = $db->sql_fetchrow($result);
			$db->sql_freeresult($result);

			$login = 1;
		}
	}

	//
	// At this point either $userdata should be populated or
	// one of the below is true
	// * Key didn't match one in the DB
	// * User does not exist
	// * User is inactive
	//
	if (!sizeof($userdata) || !is_array($userdata) || !$userdata)
	{
		$sessiondata['autologinid'] = '';
		$sessiondata['userid'] = $user_id = ANONYMOUS;
		$enable_autologin = $login = 0;

		$sql = 'SELECT *
			FROM ' . USERS_TABLE . '
			WHERE user_id = ' . (int) $user_id;
		if (!($result = $db->sql_query($sql)))
		{
			message_die(CRITICAL_ERROR, 'Error doing DB query userdata row fetch', '', __LINE__, __FILE__, $sql);
		}

		$userdata = $db->sql_fetchrow($result);
		$db->sql_freeresult($result);
	}


	//
	// Initial ban check against user id, IP and email address
	//
	preg_match('/(..)(..)(..)(..)/', $user_ip, $user_ip_parts);

	$sql = "SELECT ban_ip, ban_userid, ban_email 
		FROM " . BANLIST_TABLE . " 
		WHERE ban_ip IN ('" . $user_ip_parts[1] . $user_ip_parts[2] . $user_ip_parts[3] . $user_ip_parts[4] . "', '" . $user_ip_parts[1] . $user_ip_parts[2] . $user_ip_parts[3] . "ff', '" . $user_ip_parts[1] . $user_ip_parts[2] . "ffff', '" . $user_ip_parts[1] . "ffffff')
			OR ban_userid = $user_id";
	if ( $user_id != ANONYMOUS )
	{
		$sql .= " OR ban_email LIKE '" . str_replace("\'", "''", $userdata['user_email']) . "' 
			OR ban_email LIKE '" . substr(str_replace("\'", "''", $userdata['user_email']), strpos(str_replace("\'", "''", $userdata['user_email']), "@")) . "'";
	}
	if ( !($result = $db->sql_query($sql)) )
	{
		message_die(CRITICAL_ERROR, 'Could not obtain ban information', '', __LINE__, __FILE__, $sql);
	}

	if ( $ban_info = $db->sql_fetchrow($result) )
	{
		if ( $ban_info['ban_ip'] || $ban_info['ban_userid'] || $ban_info['ban_email'] )
		{
			message_die(CRITICAL_MESSAGE, 'You_been_banned');
		}
	}

	//
	// Create or update the session
	//
	$sql = "UPDATE " . SESSIONS_TABLE . "
		SET session_user_id = $user_id, session_start = $current_time, session_time = $current_time, session_page = $page_id, session_logged_in = $login, session_admin = $admin
		WHERE session_id = '" . $session_id . "' 
			AND session_ip = '$user_ip'";
	if ( !$db->sql_query($sql) || !$db->sql_affectedrows() )
	{
		$session_id = md5(dss_rand());

		$sql = "INSERT INTO " . SESSIONS_TABLE . "
			(session_id, session_user_id, session_start, session_time, session_ip, session_page, session_logged_in, session_admin)
			VALUES ('$session_id', $user_id, $current_time, $current_time, '$user_ip', $page_id, $login, $admin)";
		if ( !$db->sql_query($sql) )
		{
			message_die(CRITICAL_ERROR, 'Error creating new session', '', __LINE__, __FILE__, $sql);
		}
	}

	if ( $user_id != ANONYMOUS )
	{
		$last_visit = ( $userdata['user_session_time'] > 0 ) ? $userdata['user_session_time'] : $current_time; 

		if (!$admin)
		{
			$sql = "UPDATE " . USERS_TABLE . " 
				SET user_session_time = $current_time, user_session_page = $page_id, user_lastvisit = $last_visit
				WHERE user_id = $user_id";
			if ( !$db->sql_query($sql) )
			{
				message_die(CRITICAL_ERROR, 'Error updating last visit time', '', __LINE__, __FILE__, $sql);
			}
		}

		$userdata['user_lastvisit'] = $last_visit;

		//
		// Regenerate the auto-login key
		//
		if ($enable_autologin)
		{
			$auto_login_key = dss_rand() . dss_rand();
			
			if (isset($sessiondata['autologinid']) && (string) $sessiondata['autologinid'] != '')
			{
				$sql = 'UPDATE ' . SESSIONS_KEYS_TABLE . "
					SET last_ip = '$user_ip', key_id = '" . md5($auto_login_key) . "', last_login = $current_time
					WHERE key_id = '" . md5($sessiondata['autologinid']) . "'";
			}
			else
			{
				$sql = 'INSERT INTO ' . SESSIONS_KEYS_TABLE . "(key_id, user_id, last_ip, last_login)
					VALUES ('" . md5($auto_login_key) . "', $user_id, '$user_ip', $current_time)";
			}

			if ( !$db->sql_query($sql) )
			{
				message_die(CRITICAL_ERROR, 'Error updating session key', '', __LINE__, __FILE__, $sql);
			}
			
			$sessiondata['autologinid'] = $auto_login_key;
			unset($auto_login_key);
		}
		else
		{
			$sessiondata['autologinid'] = '';
		}

//		$sessiondata['autologinid'] = (!$admin) ? (( $enable_autologin && $sessionmethod == SESSION_METHOD_COOKIE ) ? $auto_login_key : '') : $sessiondata['autologinid'];
		$sessiondata['userid'] = $user_id;
	}

	$userdata['session_id'] = $session_id;
	$userdata['session_ip'] = $user_ip;
	$userdata['session_user_id'] = $user_id;
	$userdata['session_logged_in'] = $login;
	$userdata['session_page'] = $page_id;
	$userdata['session_start'] = $current_time;
	$userdata['session_time'] = $current_time;
	$userdata['session_admin'] = $admin;
	$userdata['session_key'] = $sessiondata['autologinid'];

	setcookie($cookiename . '_data', serialize($sessiondata), $current_time + 31536000, $cookiepath, $cookiedomain, $cookiesecure);
	setcookie($cookiename . '_sid', $session_id, 0, $cookiepath, $cookiedomain, $cookiesecure);

	$SID = 'sid=' . $session_id;

	return $userdata;
}

//
// Checks for a given user session, tidies session table and updates user
// sessions at each page refresh
//
function session_pagestart($user_ip, $thispage_id)
{
	global $db, $lang, $board_config;
	global $HTTP_COOKIE_VARS, $HTTP_GET_VARS, $SID;

	$cookiename = $board_config['cookie_name'];
	$cookiepath = $board_config['cookie_path'];
	$cookiedomain = $board_config['cookie_domain'];
	$cookiesecure = $board_config['cookie_secure'];

	$current_time = time();
	unset($userdata);

	if ( isset($HTTP_COOKIE_VARS[$cookiename . '_sid']) || isset($HTTP_COOKIE_VARS[$cookiename . '_data']) )
	{
		$sessiondata = isset( $HTTP_COOKIE_VARS[$cookiename . '_data'] ) ? unserialize(stripslashes($HTTP_COOKIE_VARS[$cookiename . '_data'])) : array();
		$session_id = isset( $HTTP_COOKIE_VARS[$cookiename . '_sid'] ) ? $HTTP_COOKIE_VARS[$cookiename . '_sid'] : '';
		$sessionmethod = SESSION_METHOD_COOKIE;
	}
	else
	{
		$sessiondata = array();
		$session_id = ( isset($HTTP_GET_VARS['sid']) ) ? $HTTP_GET_VARS['sid'] : '';
		$sessionmethod = SESSION_METHOD_GET;
	}

	// 
	if (!preg_match('/^[A-Za-z0-9]*$/', $session_id))
	{
		$session_id = '';
	}

	$thispage_id = (int) $thispage_id;

	//
	// Does a session exist?
	//
	if ( !empty($session_id) )
	{
		//
		// session_id exists so go ahead and attempt to grab all
		// data in preparation
		//
		$sql = "SELECT u.*, s.*
			FROM " . SESSIONS_TABLE . " s, " . USERS_TABLE . " u
			WHERE s.session_id = '$session_id'
				AND u.user_id = s.session_user_id";
		if ( !($result = $db->sql_query($sql)) )
		{
			message_die(CRITICAL_ERROR, 'Error doing DB query userdata row fetch', '', __LINE__, __FILE__, $sql);
		}

		$userdata = $db->sql_fetchrow($result);

		//
		// Did the session exist in the DB?
		//
		if ( isset($userdata['user_id']) )
		{
			//
			// Do not check IP assuming equivalence, if IPv4 we'll check only first 24
			// bits ... I've been told (by vHiker) this should alleviate problems with 
			// load balanced et al proxies while retaining some reliance on IP security.
			//
			$ip_check_s = substr($userdata['session_ip'], 0, 6);
			$ip_check_u = substr($user_ip, 0, 6);

			if ($ip_check_s == $ip_check_u)
			{
				$SID = ($sessionmethod == SESSION_METHOD_GET || defined('IN_ADMIN')) ? 'sid=' . $session_id : '';

				//
				// Only update session DB a minute or so after last update
				//
				if ( $current_time - $userdata['session_time'] > 60 )
				{
					// A little trick to reset session_admin on session re-usage
					$update_admin = (!defined('IN_ADMIN') && $current_time - $userdata['session_time'] > ($board_config['session_length']+60)) ? ', session_admin = 0' : '';

					$sql = "UPDATE " . SESSIONS_TABLE . " 
						SET session_time = $current_time, session_page = $thispage_id$update_admin
						WHERE session_id = '" . $userdata['session_id'] . "'";
					if ( !$db->sql_query($sql) )
					{
						message_die(CRITICAL_ERROR, 'Error updating sessions table', '', __LINE__, __FILE__, $sql);
					}

					if ( $userdata['user_id'] != ANONYMOUS )
					{
						$sql = "UPDATE " . USERS_TABLE . " 
							SET user_session_time = $current_time, user_session_page = $thispage_id
							WHERE user_id = " . $userdata['user_id'];
						if ( !$db->sql_query($sql) )
						{
							message_die(CRITICAL_ERROR, 'Error updating sessions table', '', __LINE__, __FILE__, $sql);
						}
					}

					session_clean($userdata['session_id']);

					setcookie($cookiename . '_data', serialize($sessiondata), $current_time + 31536000, $cookiepath, $cookiedomain, $cookiesecure);
					setcookie($cookiename . '_sid', $session_id, 0, $cookiepath, $cookiedomain, $cookiesecure);
				}

				// Add the session_key to the userdata array if it is set
				if ( isset($sessiondata['autologinid']) && $sessiondata['autologinid'] != '' )
				{
					$userdata['session_key'] = $sessiondata['autologinid'];
				}

				return $userdata;
			}
		}
	}

	//
	// If we reach here then no (valid) session exists. So we'll create a new one,
	// using the cookie user_id if available to pull basic user prefs.
	//
	$user_id = ( isset($sessiondata['userid']) ) ? intval($sessiondata['userid']) : ANONYMOUS;

	if ( !($userdata = session_begin($user_id, $user_ip, $thispage_id, TRUE)) )
	{
		message_die(CRITICAL_ERROR, 'Error creating user session', '', __LINE__, __FILE__, $sql);
	}

	return $userdata;

}

/**
* Terminates the specified session
* It will delete the entry in the sessions table for this session,
* remove the corresponding auto-login key and reset the cookies
*/
function session_end($session_id, $user_id)
{
	global $db, $lang, $board_config, $userdata;
	global $HTTP_COOKIE_VARS, $HTTP_GET_VARS, $SID;

	$cookiename = $board_config['cookie_name'];
	$cookiepath = $board_config['cookie_path'];
	$cookiedomain = $board_config['cookie_domain'];
	$cookiesecure = $board_config['cookie_secure'];

	$current_time = time();

	if (!preg_match('/^[A-Za-z0-9]*$/', $session_id))
	{
		return;
	}
	
	//
	// Delete existing session
	//
	$sql = 'DELETE FROM ' . SESSIONS_TABLE . " 
		WHERE session_id = '$session_id' 
			AND session_user_id = $user_id";
	if ( !$db->sql_query($sql) )
	{
		message_die(CRITICAL_ERROR, 'Error removing user session', '', __LINE__, __FILE__, $sql);
	}

	//
	// Remove this auto-login entry (if applicable)
	//
	if ( isset($userdata['session_key']) && $userdata['session_key'] != '' )
	{
		$autologin_key = md5($userdata['session_key']);
		$sql = 'DELETE FROM ' . SESSIONS_KEYS_TABLE . '
			WHERE user_id = ' . (int) $user_id . "
				AND key_id = '$autologin_key'";
		if ( !$db->sql_query($sql) )
		{
			message_die(CRITICAL_ERROR, 'Error removing auto-login key', '', __LINE__, __FILE__, $sql);
		}
	}

	//
	// We expect that message_die will be called after this function,
	// but just in case it isn't, reset $userdata to the details for a guest
	//
	$sql = 'SELECT *
		FROM ' . USERS_TABLE . '
		WHERE user_id = ' . ANONYMOUS;
	if ( !($result = $db->sql_query($sql)) )
	{
		message_die(CRITICAL_ERROR, 'Error obtaining user details', '', __LINE__, __FILE__, $sql);
	}
	if ( !($userdata = $db->sql_fetchrow($result)) )
	{
		message_die(CRITICAL_ERROR, 'Error obtaining user details', '', __LINE__, __FILE__, $sql);
	}
	$db->sql_freeresult($result);


	setcookie($cookiename . '_data', '', $current_time - 31536000, $cookiepath, $cookiedomain, $cookiesecure);
	setcookie($cookiename . '_sid', '', $current_time - 31536000, $cookiepath, $cookiedomain, $cookiesecure);

	return true;
}

/**
* Removes expired sessions and auto-login keys from the database
*/
function session_clean($session_id)
{
	global $board_config, $db;

	//
	// Delete expired sessions
	//
	$sql = 'DELETE FROM ' . SESSIONS_TABLE . ' 
		WHERE session_time < ' . (time() - (int) $board_config['session_length']) . " 
			AND session_id <> '$session_id'";
	if ( !$db->sql_query($sql) )
	{
		message_die(CRITICAL_ERROR, 'Error clearing sessions table', '', __LINE__, __FILE__, $sql);
	}

	//
	// Delete expired auto-login keys
	// If max_autologin_time is not set then keys will never be deleted
	// (same behaviour as old 2.0.x session code)
	//
	if (!empty($board_config['max_autologin_time']) && $board_config['max_autologin_time'] > 0)
	{
		$sql = 'DELETE FROM ' . SESSIONS_KEYS_TABLE . '
			WHERE last_login < ' . (time() - (86400 * (int) $board_config['max_autologin_time']));
		$db->sql_query($sql);
	}

	return true;
}

/**
* Reset all login keys for the specified user
* Called on password changes
*/
function session_reset_keys($user_id, $user_ip)
{
	global $db, $userdata, $board_config;

	$key_sql = ($user_id == $userdata['user_id'] && !empty($userdata['session_key'])) ? "AND key_id != '" . md5($userdata['session_key']) . "'" : '';

	$sql = 'DELETE FROM ' . SESSIONS_KEYS_TABLE . '
		WHERE user_id = ' . (int) $user_id . "
			$key_sql";

	if ( !$db->sql_query($sql) )
	{
		message_die(CRITICAL_ERROR, 'Error removing auto-login keys', '', __LINE__, __FILE__, $sql);
	}

	$where_sql = 'session_user_id = ' . (int) $user_id;
	$where_sql .= ($user_id == $userdata['user_id']) ? " AND session_id <> '" . $userdata['session_id'] . "'" : '';
	$sql = 'DELETE FROM ' . SESSIONS_TABLE . "
		WHERE $where_sql";
	if ( !$db->sql_query($sql) )
	{
		message_die(CRITICAL_ERROR, 'Error removing user session(s)', '', __LINE__, __FILE__, $sql);
	}

	if ( !empty($key_sql) )
	{
		$auto_login_key = dss_rand() . dss_rand();

		$current_time = time();
		
		$sql = 'UPDATE ' . SESSIONS_KEYS_TABLE . "
			SET last_ip = '$user_ip', key_id = '" . md5($auto_login_key) . "', last_login = $current_time
			WHERE key_id = '" . md5($userdata['session_key']) . "'";
		
		if ( !$db->sql_query($sql) )
		{
			message_die(CRITICAL_ERROR, 'Error updating session key', '', __LINE__, __FILE__, $sql);
		}

		// And now rebuild the cookie
		$sessiondata['userid'] = $user_id;
		$sessiondata['autologinid'] = $auto_login_key;
		$cookiename = $board_config['cookie_name'];
		$cookiepath = $board_config['cookie_path'];
		$cookiedomain = $board_config['cookie_domain'];
		$cookiesecure = $board_config['cookie_secure'];

		setcookie($cookiename . '_data', serialize($sessiondata), $current_time + 31536000, $cookiepath, $cookiedomain, $cookiesecure);
		
		$userdata['session_key'] = $auto_login_key;
		unset($sessiondata);
		unset($auto_login_key);
	}
}

//
// Append $SID to a url. Borrowed from phplib and modified. This is an
// extra routine utilised by the session code above and acts as a wrapper
// around every single URL and form action. If you replace the session
// code you must include this routine, even if it's empty.
//
function append_sid($url, $non_html_amp = false)
{
	global $SID;

	if ( !empty($SID) && !preg_match('#sid=#', $url) )
	{
		$url .= ( ( strpos($url, '?') !== false ) ?  ( ( $non_html_amp ) ? '&' : '&amp;' ) : '?' ) . $SID;
	}

	return $url;
}

?>

Session from login.php

<?php
/***************************************************************************
 *                                login.php
 *                            -------------------
 *   begin                : Saturday, Feb 13, 2001
 *   copyright            : (C) 2001 The phpBB Group
 *   email                : support@phpbb.com
 *
 *   $Id: login.php 6772 2006-12-16 13:11:28Z acydburn $
 *
 *
 ***************************************************************************/

/***************************************************************************
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 ***************************************************************************/

//
// Allow people to reach login page if
// board is shut down
//
define("IN_LOGIN", true);

define('IN_PHPBB', true);
$phpbb_root_path = './';
include($phpbb_root_path . 'extension.inc');
include($phpbb_root_path . 'common.'.$phpEx);

//
// Set page ID for session management
//
$userdata = session_pagestart($user_ip, PAGE_LOGIN);
init_userprefs($userdata);
//
// End session management
//

// session id check
if (!empty($HTTP_POST_VARS['sid']) || !empty($HTTP_GET_VARS['sid']))
{
	$sid = (!empty($HTTP_POST_VARS['sid'])) ? $HTTP_POST_VARS['sid'] : $HTTP_GET_VARS['sid'];
}
else
{
	$sid = '';
}

if( isset($HTTP_POST_VARS['login']) || isset($HTTP_GET_VARS['login']) || isset($HTTP_POST_VARS['logout']) || isset($HTTP_GET_VARS['logout']) )
{
	if( ( isset($HTTP_POST_VARS['login']) || isset($HTTP_GET_VARS['login']) ) && (!$userdata['session_logged_in'] || isset($HTTP_POST_VARS['admin'])) )
	{
		$username = isset($HTTP_POST_VARS['username']) ? phpbb_clean_username($HTTP_POST_VARS['username']) : '';
		$password = isset($HTTP_POST_VARS['password']) ? $HTTP_POST_VARS['password'] : '';

		$sql = "SELECT user_id, username, user_password, user_active, user_level, user_login_tries, user_last_login_try
			FROM " . USERS_TABLE . "
			WHERE username = '" . str_replace("\\'", "''", $username) . "'";
		if ( !($result = $db->sql_query($sql)) )
		{
			message_die(GENERAL_ERROR, 'Error in obtaining userdata', '', __LINE__, __FILE__, $sql);
		}

		if( $row = $db->sql_fetchrow($result) )
		{
			if( $row['user_level'] != ADMIN && $board_config['board_disable'] )
			{
				redirect(append_sid("index.$phpEx", true));
			}
			else
			{
				// If the last login is more than x minutes ago, then reset the login tries/time
				if ($row['user_last_login_try'] && $board_config['login_reset_time'] && $row['user_last_login_try'] < (time() - ($board_config['login_reset_time'] * 60)))
				{
					$db->sql_query('UPDATE ' . USERS_TABLE . ' SET user_login_tries = 0, user_last_login_try = 0 WHERE user_id = ' . $row['user_id']);
					$row['user_last_login_try'] = $row['user_login_tries'] = 0;
				}
				
				// Check to see if user is allowed to login again... if his tries are exceeded
				if ($row['user_last_login_try'] && $board_config['login_reset_time'] && $board_config['max_login_attempts'] && 
					$row['user_last_login_try'] >= (time() - ($board_config['login_reset_time'] * 60)) && $row['user_login_tries'] >= $board_config['max_login_attempts'] && $userdata['user_level'] != ADMIN)
				{
					message_die(GENERAL_MESSAGE, sprintf($lang['Login_attempts_exceeded'], $board_config['max_login_attempts'], $board_config['login_reset_time']));
				}

				if( md5($password) == $row['user_password'] && $row['user_active'] )
				{
					$autologin = ( isset($HTTP_POST_VARS['autologin']) ) ? TRUE : 0;

					$admin = (isset($HTTP_POST_VARS['admin'])) ? 1 : 0;
					$session_id = session_begin($row['user_id'], $user_ip, PAGE_INDEX, FALSE, $autologin, $admin);

					// Reset login tries
					$db->sql_query('UPDATE ' . USERS_TABLE . ' SET user_login_tries = 0, user_last_login_try = 0 WHERE user_id = ' . $row['user_id']);

					if( $session_id )
					{
						$url = ( !empty($HTTP_POST_VARS['redirect']) ) ? str_replace('&amp;', '&', htmlspecialchars($HTTP_POST_VARS['redirect'])) : "index.$phpEx";
						redirect(append_sid($url, true));
					}
					else
					{
						message_die(CRITICAL_ERROR, "Couldn't start session : login", "", __LINE__, __FILE__);
					}
				}
				// Only store a failed login attempt for an active user - inactive users can't login even with a correct password
				elseif( $row['user_active'] )
				{
					// Save login tries and last login
					if ($row['user_id'] != ANONYMOUS)
					{
						$sql = 'UPDATE ' . USERS_TABLE . '
							SET user_login_tries = user_login_tries + 1, user_last_login_try = ' . time() . '
							WHERE user_id = ' . $row['user_id'];
						$db->sql_query($sql);
					}
				}

				$redirect = ( !empty($HTTP_POST_VARS['redirect']) ) ? str_replace('&amp;', '&', htmlspecialchars($HTTP_POST_VARS['redirect'])) : '';
				$redirect = str_replace('?', '&', $redirect);

				if (strstr(urldecode($redirect), "\n") || strstr(urldecode($redirect), "\r") || strstr(urldecode($redirect), ';url'))
				{
					message_die(GENERAL_ERROR, 'Tried to redirect to potentially insecure url.');
				}

				$template->assign_vars(array(
					'META' => "<meta http-equiv=\"refresh\" content=\"3;url=login.$phpEx?redirect=$redirect\">")
				);

				$message = $lang['Error_login'] . '<br /><br />' . sprintf($lang['Click_return_login'], "<a href=\"login.$phpEx?redirect=$redirect\">", '</a>') . '<br /><br />' .  sprintf($lang['Click_return_index'], '<a href="' . append_sid("index.$phpEx") . '">', '</a>');

				message_die(GENERAL_MESSAGE, $message);
			}
		}
		else
		{
			$redirect = ( !empty($HTTP_POST_VARS['redirect']) ) ? str_replace('&amp;', '&', htmlspecialchars($HTTP_POST_VARS['redirect'])) : "";
			$redirect = str_replace("?", "&", $redirect);

			if (strstr(urldecode($redirect), "\n") || strstr(urldecode($redirect), "\r") || strstr(urldecode($redirect), ';url'))
			{
				message_die(GENERAL_ERROR, 'Tried to redirect to potentially insecure url.');
			}

			$template->assign_vars(array(
				'META' => "<meta http-equiv=\"refresh\" content=\"3;url=login.$phpEx?redirect=$redirect\">")
			);

			$message = $lang['Error_login'] . '<br /><br />' . sprintf($lang['Click_return_login'], "<a href=\"login.$phpEx?redirect=$redirect\">", '</a>') . '<br /><br />' .  sprintf($lang['Click_return_index'], '<a href="' . append_sid("index.$phpEx") . '">', '</a>');

			message_die(GENERAL_MESSAGE, $message);
		}
	}
	else if( ( isset($HTTP_GET_VARS['logout']) || isset($HTTP_POST_VARS['logout']) ) && $userdata['session_logged_in'] )
	{
		// session id check
		if ($sid == '' || $sid != $userdata['session_id'])
		{
			message_die(GENERAL_ERROR, 'Invalid_session');
		}

		if( $userdata['session_logged_in'] )
		{
			session_end($userdata['session_id'], $userdata['user_id']);
		}

		if (!empty($HTTP_POST_VARS['redirect']) || !empty($HTTP_GET_VARS['redirect']))
		{
			$url = (!empty($HTTP_POST_VARS['redirect'])) ? htmlspecialchars($HTTP_POST_VARS['redirect']) : htmlspecialchars($HTTP_GET_VARS['redirect']);
			$url = str_replace('&amp;', '&', $url);
			redirect(append_sid($url, true));
		}
		else
		{
			redirect(append_sid("index.$phpEx", true));
		}
	}
	else
	{
		$url = ( !empty($HTTP_POST_VARS['redirect']) ) ? str_replace('&amp;', '&', htmlspecialchars($HTTP_POST_VARS['redirect'])) : "index.$phpEx";
		redirect(append_sid($url, true));
	}
}
else
{
	//
	// Do a full login page dohickey if
	// user not already logged in
	//
	if( !$userdata['session_logged_in'] || (isset($HTTP_GET_VARS['admin']) && $userdata['session_logged_in'] && $userdata['user_level'] == ADMIN))
	{
		$page_title = $lang['Login'];
		include($phpbb_root_path . 'includes/page_header.'.$phpEx);

		$template->set_filenames(array(
			'body' => 'login_body.tpl')
		);

		$forward_page = '';

		if( isset($HTTP_POST_VARS['redirect']) || isset($HTTP_GET_VARS['redirect']) )
		{
			$forward_to = $HTTP_SERVER_VARS['QUERY_STRING'];

			if( preg_match("/^redirect=([a-z0-9\.#\/\?&=\+\-_]+)/si", $forward_to, $forward_matches) )
			{
				$forward_to = ( !empty($forward_matches[3]) ) ? $forward_matches[3] : $forward_matches[1];
				$forward_match = explode('&', $forward_to);

				if(count($forward_match) > 1)
				{
					for($i = 1; $i < count($forward_match); $i++)
					{
						if( !ereg("sid=", $forward_match[$i]) )
						{
							if( $forward_page != '' )
							{
								$forward_page .= '&';
							}
							$forward_page .= $forward_match[$i];
						}
					}
					$forward_page = $forward_match[0] . '?' . $forward_page;
				}
				else
				{
					$forward_page = $forward_match[0];
				}
			}
		}

		$username = ( $userdata['user_id'] != ANONYMOUS ) ? $userdata['username'] : '';

		$s_hidden_fields = '<input type="hidden" name="redirect" value="' . $forward_page . '" />';
		$s_hidden_fields .= (isset($HTTP_GET_VARS['admin'])) ? '<input type="hidden" name="admin" value="1" />' : '';

		make_jumpbox('viewforum.'.$phpEx);
		$template->assign_vars(array(
			'USERNAME' => $username,

			'L_ENTER_PASSWORD' => (isset($HTTP_GET_VARS['admin'])) ? $lang['Admin_reauthenticate'] : $lang['Enter_password'],
			'L_SEND_PASSWORD' => $lang['Forgotten_password'],

			'U_SEND_PASSWORD' => append_sid("profile.$phpEx?mode=sendpassword"),

			'S_HIDDEN_FIELDS' => $s_hidden_fields)
		);

		$template->pparse('body');

		include($phpbb_root_path . 'includes/page_tail.'.$phpEx);
	}
	else
	{
		redirect(append_sid("index.$phpEx", true));
	}

}

?>

Session for index page

//
// Start session management
//
$userdata = session_pagestart($user_ip, PAGE_INDEX);
init_userprefs($userdata);
//
// End session management
//

I hope that this will help you out some.

//Have seen these errors//

User id is :c13964
First name is :Lord
Found user is:1
LoginRS:Resource id #3
LoginRSQuerySELECT user_id, first_name FROM adminprofile WHERE username='nk7s86' AND password='hamachi'
Recordrow Array // I REALLY DO NOT UNDERSTAND ABOUT THE RECORDROW "print" ARRAY

These are the Error Messages in FireFox

Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at C:\Program Files\xampp\htdocs\cycle270208\admin.php:1) in C:\Program Files\xampp\htdocs\cycle270208\admin.php on line 46

Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at C:\Program Files\xampp\htdocs\cycle270208\admin.php:1) in C:\Program Files\xampp\htdocs\cycle270208\admin.php on line 46
c13964Dr.

~~~~~~~~~~~~Below is the Code I tried~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

$loginUsername = get_magic_quotes_gpc() ? $loginUsername : addslashes($loginUsername);
  $password = get_magic_quotes_gpc() ? $password : addslashes($password);
  
  $LoginRS_query = "SELECT user_id, first_name FROM adminprofile WHERE username='$loginUsername' AND password='$loginPassword'";
  $LoginRS = mysql_query($LoginRS_query) or die(mysql_error());
  
  
  $loginFoundUser = mysql_num_rows($LoginRS);
  $record_row = mysql_fetch_array($LoginRS);
  $user_id = $record_row['user_id'];
  $first_name = $record_row['first_name'];
  print "User id is :". $user_id; 
  print "First name is :". $first_name;
  print "Found user is:". $loginFoundUser;
  print "LoginRS:". $LoginRS;
  print "LoginRSQuery". $LoginRS_query;
  print "Recordrow". $record_row;
  
  if ($loginFoundUser) {
    
	session_name ('YourVisitID');
	session_start();
	$_SESSION['user_id'] = $record_row['user_id'];
	$_SESSION['first_name'] = $record_row['first_name'];
	echo $_SESSION['user_id'];
	echo $_SESSION['first_name'];
	//$_SESSION['agent'] = md5($_SERVER['HTTP_USER_AGENT']);
	//header( "Location: validated.php" );
    //echo "<script type='text/javascript'>location.href='$MM_redirectLoginSuccess';</script>";
	exit();

Please advise.

You can't print anything before session_start. Thats why you are getting those errors. And as I see it, its assigning the values to the session variables. Comment the print/echo lines and try redirecting it to a dummy page. If that doesn't work, I dunno what else to try/recommend.

Yet, still left with these 2 errors

Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at C:\Program Files\xampp\htdocs\cycle270208\admin.php:1) in C:\Program Files\xampp\htdocs\cycle270208\admin.php on line 46

Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at C:\Program Files\xampp\htdocs\cycle270208\admin.php:1) in C:\Program Files\xampp\htdocs\cycle270208\admin.php on line 46

Please help.

As I said earlier, You shouldn't have any output, not an echo/print statement or a html tag before session_start. Do 1 thing. put session_name and session_start on top of the page.

Even though I've canceled all the echo's and the print statements, the same error keep on appearing. The errors keep on pointing to start_session(); Together I've attached the final modified codes for your reference.

admin.php

<?php
session_name ('VisitID');
session_start();

// connection to MySQL server
mysql_connect('localhost','root','');
mysql_select_db('administration');

if (isset($_POST['username'])) {
  $loginUsername=$_POST['username'];
  $loginPassword=$_POST['password']; 
  //$MM_redirectLoginSuccess = "test2.php";
  $MM_redirectLoginSuccess = "validated.php";
  $MM_redirectLoginFailed = "admin.php";
  $MM_redirecttoReferrer = true;
  
  $errors = array();
  
	 if(empty($_POST['username'])) {
		$errors[] = 'You think whom going to fill up the USERNAME for you?';
	 }	
	 if(empty($_POST['password'])) {
		$errors[] = 'You think whom going to fill up the PASSWORD for you?';
	 }	
	if (empty($errors)) {
	
  $loginUsername = get_magic_quotes_gpc() ? $loginUsername : addslashes($loginUsername);
  $password = get_magic_quotes_gpc() ? $password : addslashes($password);
  
  $LoginRS_query = "SELECT user_id, first_name FROM adminprofile WHERE username='$loginUsername' AND password='$loginPassword'";
  $LoginRS = mysql_query($LoginRS_query) or die(mysql_error());
  
  $loginFoundUser = mysql_num_rows($LoginRS);
  $record_row = mysql_fetch_array($LoginRS);
  $user_id = $record_row['user_id'];
  $first_name = $record_row['first_name'];
  
  if ($loginFoundUser) {
   	//session_name ('VisitID');
	//session_start();
	$_SESSION['user_id'] = $record_row['user_id'];
	$_SESSION['first_name'] = $record_row['first_name'];
	
    echo "<script type='text/javascript'>location.href='$MM_redirectLoginSuccess';</script>";
	exit();
	}
  else {
  
    echo "<script type='text/javascript'>location.href='$MM_redirectLoginFailed';</script>";
}
}
mysql_close();
}

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
		
<html>
<head>
	<title>Cycle Tracks Portal - Administrator's Page</title>
		<style type="text/css" media="all">@import "images/style.css";
</style>
	<link rel="alternate" type="application/rss+xml" title="RSS 2.0" href="rss/" />
</head>

<body>
<div class="content">
	<div class="topmenu">
		<div class="date_"><? echo date('l dS \of F Y'); ?></div>
	</div>
	
	<div id="submenu">
	</div>
		
	<div class="cycle">
		<div class="title" style="text-align: center; width: 179px">
			<sup>
			<span class="copynresv">©</span></sup>CYCLE TRACKS<sup><span class="copynresv">®</span></sup></div>
		<div class="slogan" style="width: 223px; height: 11px">&quot;We are ONE of the BEST and NOT like the REST!</div>
	</div>
	
	<div class="nav">
		<ul>
			<li><a href="#">HOME</a> | </li> 
			<li><a href="#">INSTRUCTIONS</a> | </li>
			<li><a href="#">FIND</a> | </li> 
			<li><a href="#">DISPLAY</a> | </li>
			<li><a href="#">ADMIN</a> | </li>
			<li><a href="#">CREDITS</a></li>
		</ul>
	</div>
	<br>
	</br>
	<table style="width: 764px; height: 141px;"align="center" cellspacing="1">
		<tr>
			<td>
			<form name="adminInput" action="admin.php" method="post" style="height: 99px">
			<table style="width: 284px; height: 56px" align="center">
				<tr>
					<td style="width: 189px; height: 21px;" class="uspstyle">Username</td>
					<td style="width: 191px; height: 21px;">
						<input type="text" name="username" size="30"/>
					</td>
				</tr>
				<tr>
					<td style="width: 189px; height: 21px;" class="uspstyle">Password</td>
					<td style="width: 191px; height: 21px;">
					<input type="password" name="password" size="30"/>
					</td>
				</tr>
				<tr>
					<td style="width: 189px; height: 36px;" class="uspstyle"></td>
					<td style="width: 191px; height: 36px;">
					<table style="width: 100%">
						<tr>
							<td style="width: 89px">
							<input type="submit" name="submit" value="Login" class="uspstyle2" style="height: 23px; width: 88px"/></td>
							<td style="width: 89px">
							<input type="reset" name="reset" value="Clear" class="uspstyle2" style="height: 23px; width: 88px"/></td>
						</tr>
					</table>
					</td>
				</tr>
			</table>
			</form>
				<?php
				if (!empty($errors)) { // Print any error messages.
					echo '<h1 class="errorLog1">Error!</h1>
					<p class="errorLog2">The following error(s) occurred:<br />';
					foreach ($errors as $msg) { // Print each error.
						echo " - $msg<br />\n";
					}
					echo '</p><p class="errorLog3">Please try again.</p>';
				}
				?>
			</td>
		</tr>
	</table>
	<div class="footer">
		<div class="padding">
			&copy; Copyright Cycle Tracks <span>®</span></div>
	</div>
	
</div>

</body>
</html>

<?php
?>

validated.php

<?php

session_name ('VisitID');
session_start(); // Start the session.
//print_r($_SESSION);
$MM_redirectLoginFailed = "admin.php";
$MM_redirecttoReferrer = true;
// If no session value is present, redirect the user.
if(! isset($_SESSION['user_id']) || ! isset($_SESSION['first_name'])) {
	echo "<script type='text/javascript'>location.href='$MM_redirectLoginFailed';</script>";
	exit(); // Quit the script.
}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
	<title>Cycle Tracks Portal - Administrator's Page</title>
		<style type="text/css" media="all">@import "images/style.css";
		</style>
	<link rel="alternate" type="application/rss+xml" title="RSS 2.0" href="rss/" />
	<script language="javascript">
		if(document.images) {
			imageAddBefore = new Image
			imageAddAfter = new Image
			imageAddBefore.src = "images/add_before.png"
			imageAddAfter.src = "images/add_after.png"
			imageEditBefore = new Image
			imageEditAfter = new Image
			imageEditBefore.src = "images/edit_before.png"
			imageEditAfter.src = "images/edit_after.png"
			imageDelBefore = new Image
			imageDelAfter = new Image
			imageDelBefore.src = "images/del_before.png"
			imageDelAfter.src = "images/del_after.png"
		}
	</script>
</head>

<body>
<div class="content">
	<div class="topmenu">
		<div class="date_"><? echo date('l dS \of F Y'); ?></div>
	</div>
	
	<div id="submenu">
	Validation Successful !<br />
	Administrator&#39;s Page !</div>
		
	<div class="cycle">
		<div class="title" style="text-align: center; width: 179px">
			<sup>
			<span class="copynresv">©</span></sup>CYCLE TRACKS<sup><span class="copynresv">®</span></sup></div>
		<div class="slogan" style="width: 223px; height: 11px">&quot;We are ONE of the BEST and NOT like the REST!</div>
	</div>
	
	<div class="nav">
		<ul>
			<li><a href="index.php">HOME</a> | </li> 
			<li><a href="#">INSTRUCTIONS</a> | </li>
			<li><a href="#">FIND</a> | </li> 
			<li><a href="#">DISPLAY</a> | </li>
			<li><a href="admin.php">ADMIN</a> | </li>
			<li><a href="#">CREDITS</a></li>
		</ul>
	</div>
	
	<table style="width: 764px; height: 141px;"align="left" cellspacing="1">
		<tr>
			<td>
				<table style="width: 100%">
					<tr>
						<td style="width: 249px" class="imgADE">
							<a href ="add.php" onmouseover = "document.addbut.src =imageAddAfter.src" onmouseout = "document.addbut.src =imageAddBefore.src">
								<img src = "images/add_before.png" alt="Add Cycle" name = "addbut" width="156" height="34"/>
							</a>
						</td>
						<td style="width: 248px" class="imgADE">
							<a href ="edit.php" onmouseover = "document.editbut.src =imageEditAfter.src" onmouseout = "document.editbut.src =imageEditBefore.src">
								<img src = "images/edit_before.png" alt="Edit Cycle" name = "editbut" width="156" height="34"/>
							</a>
						</td>
						<td style="width: 249px" class="imgADE">
							<a href ="del.php" onmouseover = "document.delbut.src =imageDelAfter.src" onmouseout = "document.delbut.src =imageDelBefore.src">
								<img src = "images/del_before.png" alt="Del Cycle" name = "delbut" width="156" height="34"/>
							</a>
						</td>
					</tr>
				</table>
			</td>
		</tr>
	</table>
	
	<div class="footer">
		<div class="padding">
			&copy; Copyright Cycle Tracks <span>®</span></div>
	</div>
		
</div>
</body>
</html>

These were the complete codes, it might be useful. I've done a lots of study before posting here, you guys are my last hope. Please help.

I checked your code. I have a table called user and I checked if it works. And it does! Your code works on my computer. Check if cookies are enabled. See, this is what I have. This is admin.php

<?php
session_name ('VisitID');
session_start();

// connection to MySQL server
mysql_connect('localhost','root','');
mysql_select_db('seacon');

if (isset($_POST['username'])) {
  $loginUsername=$_POST['username'];
  $loginPassword=$_POST['password']; 
  //$MM_redirectLoginSuccess = "test2.php";
  $MM_redirectLoginSuccess = "validated.php";
  $MM_redirectLoginFailed = "admin.php";
  $MM_redirecttoReferrer = true;
  
  $errors = array();
  
	 if(empty($_POST['username'])) {
		$errors[] = 'You think whom going to fill up the USERNAME for you?';
	 }	
	 if(empty($_POST['password'])) {
		$errors[] = 'You think whom going to fill up the PASSWORD for you?';
	 }	
	if (empty($errors)) {
	
  $loginUsername = get_magic_quotes_gpc() ? $loginUsername : addslashes($loginUsername);
  $password = get_magic_quotes_gpc() ? $password : addslashes($password);
  
  $LoginRS_query = "SELECT user_id, first_name FROM user WHERE login_name='$loginUsername' AND password='$loginPassword'";
  $LoginRS = mysql_query($LoginRS_query) or die(mysql_error());
  
  $loginFoundUser = mysql_num_rows($LoginRS);
  $record_row = mysql_fetch_array($LoginRS);
  $user_id = $record_row['user_id'];
  $first_name = $record_row['first_name'];
  
  if ($loginFoundUser) {
   	//session_name ('VisitID');
	//session_start();
	$_SESSION['user_id'] = $record_row['user_id'];
	$_SESSION['first_name'] = $record_row['first_name'];
	
    echo "<script type='text/javascript'>location.href='$MM_redirectLoginSuccess';</script>";
	exit();
	}
  else {
  
    echo "<script type='text/javascript'>location.href='$MM_redirectLoginFailed';</script>";
}
}
mysql_close();
}

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
		
<html>
<head>
	<title>Cycle Tracks Portal - Administrator's Page</title>
		<style type="text/css" media="all">@import "images/style.css";
</style>
	<link rel="alternate" type="application/rss+xml" title="RSS 2.0" href="rss/" />
</head>

<body>
<div class="content">
	<div class="topmenu">
		<div class="date_"><? echo date('l dS \of F Y'); ?></div>
	</div>
	
	<div id="submenu">
	</div>
		
	<div class="cycle">
		<div class="title" style="text-align: center; width: 179px">
			<sup>
			<span class="copynresv">©</span></sup>CYCLE TRACKS<sup><span class="copynresv">®</span></sup></div>
		<div class="slogan" style="width: 223px; height: 11px">&quot;We are ONE of the BEST and NOT like the REST!</div>
	</div>
	
	<div class="nav">
		<ul>
			<li><a href="#">HOME</a> | </li> 
			<li><a href="#">INSTRUCTIONS</a> | </li>
			<li><a href="#">FIND</a> | </li> 
			<li><a href="#">DISPLAY</a> | </li>
			<li><a href="#">ADMIN</a> | </li>
			<li><a href="#">CREDITS</a></li>
		</ul>
	</div>
	<br>
	</br>
	<table style="width: 764px; height: 141px;"align="center" cellspacing="1">
		<tr>
			<td>
			<form name="adminInput" action="admin.php" method="post" style="height: 99px">
			<table style="width: 284px; height: 56px" align="center">
				<tr>
					<td style="width: 189px; height: 21px;" class="uspstyle">Username</td>
					<td style="width: 191px; height: 21px;">
						<input type="text" name="username" size="30"/>
					</td>
				</tr>
				<tr>
					<td style="width: 189px; height: 21px;" class="uspstyle">Password</td>
					<td style="width: 191px; height: 21px;">
					<input type="password" name="password" size="30"/>
					</td>
				</tr>
				<tr>
					<td style="width: 189px; height: 36px;" class="uspstyle"></td>
					<td style="width: 191px; height: 36px;">
					<table style="width: 100%">
						<tr>
							<td style="width: 89px">
							<input type="submit" name="submit" value="Login" class="uspstyle2" style="height: 23px; width: 88px"/></td>
							<td style="width: 89px">
							<input type="reset" name="reset" value="Clear" class="uspstyle2" style="height: 23px; width: 88px"/></td>
						</tr>
					</table>
					</td>
				</tr>
			</table>
			</form>
				<?php
				if (!empty($errors)) { // Print any error messages.
					echo '<h1 class="errorLog1">Error!</h1>
					<p class="errorLog2">The following error(s) occurred:<br />';
					foreach ($errors as $msg) { // Print each error.
						echo " - $msg<br />\n";
					}
					echo '</p><p class="errorLog3">Please try again.</p>';
				}
				?>
			</td>
		</tr>
	</table>
	<div class="footer">
		<div class="padding">
			&copy; Copyright Cycle Tracks <span>®</span></div>
	</div>
	
</div>

</body>
</html>

<?php
?>

And this is validated.php

<?php

session_name ('VisitID');
session_start(); // Start the session.
print_r($_SESSION);
$MM_redirectLoginFailed = "admin.php";
$MM_redirecttoReferrer = true;
// If no session value is present, redirect the user.
if(! isset($_SESSION['user_id']) || ! isset($_SESSION['first_name'])) {
	echo "<script type='text/javascript'>location.href='$MM_redirectLoginFailed';</script>";
	exit(); // Quit the script.
}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
	<title>Cycle Tracks Portal - Administrator's Page</title>
		<style type="text/css" media="all">@import "images/style.css";
		</style>
	<link rel="alternate" type="application/rss+xml" title="RSS 2.0" href="rss/" />
	<script language="javascript">
		if(document.images) {
			imageAddBefore = new Image
			imageAddAfter = new Image
			imageAddBefore.src = "images/add_before.png"
			imageAddAfter.src = "images/add_after.png"
			imageEditBefore = new Image
			imageEditAfter = new Image
			imageEditBefore.src = "images/edit_before.png"
			imageEditAfter.src = "images/edit_after.png"
			imageDelBefore = new Image
			imageDelAfter = new Image
			imageDelBefore.src = "images/del_before.png"
			imageDelAfter.src = "images/del_after.png"
		}
	</script>
</head>

<body>
<div class="content">
	<div class="topmenu">
		<div class="date_"><? echo date('l dS \of F Y'); ?></div>
	</div>
	
	<div id="submenu">
	Validation Successful !<br />
	Administrator's Page !</div>
		
	<div class="cycle">
		<div class="title" style="text-align: center; width: 179px">
			<sup>
			<span class="copynresv">©</span></sup>CYCLE TRACKS<sup><span class="copynresv">®</span></sup></div>
		<div class="slogan" style="width: 223px; height: 11px">&quot;We are ONE of the BEST and NOT like the REST!</div>
	</div>
	
	<div class="nav">
		<ul>
			<li><a href="index.php">HOME</a> | </li> 
			<li><a href="#">INSTRUCTIONS</a> | </li>
			<li><a href="#">FIND</a> | </li> 
			<li><a href="#">DISPLAY</a> | </li>
			<li><a href="admin.php">ADMIN</a> | </li>
			<li><a href="#">CREDITS</a></li>
		</ul>
	</div>
	
	<table style="width: 764px; height: 141px;"align="left" cellspacing="1">
		<tr>
			<td>
				<table style="width: 100%">
					<tr>
						<td style="width: 249px" class="imgADE">
							<a href ="add.php" onmouseover = "document.addbut.src =imageAddAfter.src" onmouseout = "document.addbut.src =imageAddBefore.src">
								<img src = "images/add_before.png" alt="Add Cycle" name = "addbut" width="156" height="34"/>
							</a>
						</td>
						<td style="width: 248px" class="imgADE">
							<a href ="edit.php" onmouseover = "document.editbut.src =imageEditAfter.src" onmouseout = "document.editbut.src =imageEditBefore.src">
								<img src = "images/edit_before.png" alt="Edit Cycle" name = "editbut" width="156" height="34"/>
							</a>
						</td>
						<td style="width: 249px" class="imgADE">
							<a href ="del.php" onmouseover = "document.delbut.src =imageDelAfter.src" onmouseout = "document.delbut.src =imageDelBefore.src">
								<img src = "images/del_before.png" alt="Del Cycle" name = "delbut" width="156" height="34"/>
							</a>
						</td>
					</tr>
				</table>
			</td>
		</tr>
	</table>
	
	<div class="footer">
		<div class="padding">
			&copy; Copyright Cycle Tracks <span>®</span></div>
	</div>
		
</div>
</body>
</html>

Hmm.. So, I think, something has to do with php settings. Can you do 1 thing. Write a simple script like this.

<?php
phpinfo();
?>

and show what's in [session].

Screenshots attached. Advise Please.

umm.. I m not sure if this will help you. But, check session.save_path exists. And, As I see in my php.ini, its,

session.save_path = "c:/wamp/tmp"

. Notice the forward slashes (and not the path).

mine like this

session.save_path = "C:\Program Files\xampp\tmp"

Then I've changed it to,

session.save_path = "C:/Program Files/xampp/tmp"

still not working.

Yeah.. Check if there is a folder called tmp in program files\xampp. Also, change \ to /.

how to do this? the folder is there but what , where and how to change?

Now the I can create the sessions, but the problem is when the first time I input the username and password then it will redirect me to the dummy page and the session will be

Array()

Then I press back and enter the username and password again, it will redirect me to the dummy page and the session will be

Array ( [user_id] => c13964 [first_name] => Dr. )

NOTE
There will errors on the admin.php even though it redirect me to the dummy page. This errors are there even before anything being inputted.

Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at C:\xampp\htdocs\cycle\admin.php:1) in C:\xampp\htdocs\cycle\admin.php on line 6

Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at C:\xampp\htdocs\cycle\admin.php:1) in C:\xampp\htdocs\cycle\admin.php on line 6

Advise please.

Cool.. atleast there is some progress.. Well, Don't redirect to the next page if there are any errors. When you say 'there will be errors on the admin.php', what errors are you talking about ?

I've already paste it under NOTE in the thread above.

Is that it ? Can you post the code of admin.php for one last time ?

admin.php

<?php
// connection to MySQL server
mysql_connect('localhost','root','');
mysql_select_db('administration');
session_name ('YourVisitID');
session_start();

if (isset($_POST['username'])) {
  $loginUsername=$_POST['username'];
  $loginPassword=$_POST['password']; 
  $MM_redirectLoginSuccess = "test2.php";
  //$MM_redirectLoginSuccess = "validated.php";
  $MM_redirectLoginFailed = "admin.php";
  $MM_redirecttoReferrer = true;
  
  $errors = array();
  
	 if(empty($_POST['username'])) {
		$errors[] = 'You think whom going to fill up the USERNAME for you?';
	 }	
	 if(empty($_POST['password'])) {
		$errors[] = 'You think whom going to fill up the PASSWORD for you?';
	 }	
	if (empty($errors)) {
	
  $loginUsername = get_magic_quotes_gpc() ? $loginUsername : addslashes($loginUsername);
  $password = get_magic_quotes_gpc() ? $password : addslashes($password);
  $LoginRS_query = "SELECT user_id, first_name FROM adminprofile WHERE username='$loginUsername' AND password='$loginPassword'";
  $LoginRS = mysql_query($LoginRS_query) or die(mysql_error());
  $loginFoundUser = mysql_num_rows($LoginRS);
  $record_row = mysql_fetch_array($LoginRS);
  
  if ($loginFoundUser) {
    
	//session_name ('YourVisitID');
	//session_start();
	$_SESSION['user_id'] = $record_row['user_id'];
	$_SESSION['first_name'] = $record_row['first_name'];

    echo "<script type='text/javascript'>location.href='$MM_redirectLoginSuccess';</script>";
	exit();
	}
  else {
  
    echo "<script type='text/javascript'>location.href='$MM_redirectLoginFailed';</script>";
}
}
mysql_close();
}

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
		
<html>
<head>
	<title>Cycle Tracks Portal - Administrator's Page</title>
		<style type="text/css" media="all">@import "images/style.css";
</style>
	<link rel="alternate" type="application/rss+xml" title="RSS 2.0" href="rss/" />
</head>

<body>
<div class="content">
	<div class="topmenu">
		<div class="date_"><? echo date('l dS \of F Y'); ?></div>
	</div>
	
	<div id="submenu">
	</div>
		
	<div class="cycle">
		<div class="title" style="text-align: center; width: 179px">
			<sup>
			<span class="copynresv">©</span></sup>CYCLE TRACKS<sup><span class="copynresv">®</span></sup></div>
		<div class="slogan" style="width: 223px; height: 11px">&quot;We are ONE of the BEST and NOT like the REST!</div>
	</div>
	
	<div class="nav">
		<ul>
			<li><a href="#">HOME</a> | </li> 
			<li><a href="#">INSTRUCTIONS</a> | </li>
			<li><a href="#">FIND</a> | </li> 
			<li><a href="#">DISPLAY</a> | </li>
			<li><a href="#">ADMIN</a> | </li>
			<li><a href="#">CREDITS</a></li>
		</ul>
	</div>
	<br>
	</br>
	<table style="width: 764px; height: 141px;"align="center" cellspacing="1">
		<tr>
			<td>
			<form name="adminInput" action="admin.php" method="post" style="height: 99px">
			<table style="width: 284px; height: 56px" align="center">
				<tr>
					<td style="width: 189px; height: 21px;" class="uspstyle">Username</td>
					<td style="width: 191px; height: 21px;">
						<input type="text" name="username" size="30"/>
					</td>
				</tr>
				<tr>
					<td style="width: 189px; height: 21px;" class="uspstyle">Password</td>
					<td style="width: 191px; height: 21px;">
					<input type="password" name="password" size="30"/>
					</td>
				</tr>
				<tr>
					<td style="width: 189px; height: 36px;" class="uspstyle"></td>
					<td style="width: 191px; height: 36px;">
					<table style="width: 100%">
						<tr>
							<td style="width: 89px">
							<input type="submit" name="submit" value="Login" class="uspstyle2" style="height: 23px; width: 88px"/></td>
							<td style="width: 89px">
							<input type="reset" name="reset" value="Clear" class="uspstyle2" style="height: 23px; width: 88px"/></td>
						</tr>
					</table>
					</td>
				</tr>
			</table>
			</form>
				<?php
				if (!empty($errors)) { // Print any error messages.
					echo '<h1 class="errorLog1">Error!</h1>
					<p class="errorLog2">The following error(s) occurred:<br />';
					foreach ($errors as $msg) { // Print each error.
						echo " - $msg<br />\n";
					}
					echo '</p><p class="errorLog3">Please try again.</p>';
				}
				?>
			</td>
		</tr>
	</table>
	<div class="footer">
		<div class="padding">
			&copy; Copyright Cycle Tracks <span>®</span></div>
	</div>
	
	
</div>

</body>
</html>

NOTE : I post the full code because the session was working when I removed the last 2 lines after the </html>. They were,

<?php
?>

only after this the session start to work.

validated.php

?php

session_name ('YourVisitID');
session_start(); // Start the session.
//print_r($_SESSION);
//$MM_redirectLoginFailed = "admin.php";
//$MM_redirecttoReferrer = true;

// If no session value is present, redirect the user.
if(! isset($_SESSION['user_id']) || ! isset($_SESSION['first_name'])) {
	$MM_redirectLoginFailed = "admin.php";
	$MM_redirecttoReferrer = true;
	echo "<script type='text/javascript'>location.href='$MM_redirectLoginFailed';</script>";
	exit(); // Quit the script.
}

?>

and the dummy page, test2.php

<?php
session_name ('YourVisitID');
session_start();
print_r($_SESSION);

if(! isset($_SESSION['user_id']) || ! isset($_SESSION['first_name'])) {
	$MM_redirectLoginFailed = "admin.php";
	$MM_redirecttoReferrer = true;
	echo "<script type='text/javascript'>location.href='$MM_redirectLoginFailed';</script>";
	exit();
	}
?>

How the session works

1. Set the admin.php to redirect the user to test2.php if a valid username and password was inputted.
2. You shall see the session printed as an empty array, e.g. Array().
3. Press the BACK button on your browser and you will back at admin.php again.
4. Now type the username and password again.
5. You will find yourself at test2.php with the session working and the array will produce the user id and first name value.
6. Any further doubt..... kindly post.

Huh! why does it work when you click the back button and enter again ? Strange. Anyway, Check if this will solve the error.

<?php
ob_start();
mysql_connect('localhost','root','');
mysql_select_db('administration');
session_name ('YourVisitID');
session_start();

if (isset($_POST['username'])) {
  $loginUsername=$_POST['username'];
  $loginPassword=$_POST['password']; 
  $MM_redirectLoginSuccess = "test2.php";
  //$MM_redirectLoginSuccess = "validated.php";
  $MM_redirectLoginFailed = "admin.php";
  $MM_redirecttoReferrer = true;
  
  $errors = array();
  
	 if(empty($_POST['username'])) {
		$errors[] = 'You think whom going to fill up the USERNAME for you?';
	 }	
	 if(empty($_POST['password'])) {
		$errors[] = 'You think whom going to fill up the PASSWORD for you?';
	 }	
	if (empty($errors)) {
	
  $loginUsername = get_magic_quotes_gpc() ? $loginUsername : addslashes($loginUsername);
  $password = get_magic_quotes_gpc() ? $password : addslashes($password);
  $LoginRS_query = "SELECT user_id, first_name FROM adminprofile WHERE username='$loginUsername' AND password='$loginPassword'";
  $LoginRS = mysql_query($LoginRS_query) or die(mysql_error());
  $loginFoundUser = mysql_num_rows($LoginRS);
  $record_row = mysql_fetch_array($LoginRS);
  
  if ($loginFoundUser) {
    
	//session_name ('YourVisitID');
	//session_start();
	$_SESSION['user_id'] = $record_row['user_id'];
	$_SESSION['first_name'] = $record_row['first_name'];

    echo "<script type='text/javascript'>location.href='$MM_redirectLoginSuccess';</script>";
	exit();
	}
  else {
  
    echo "<script type='text/javascript'>location.href='$MM_redirectLoginFailed';</script>";
}
}
mysql_close();
}

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
		
<html>
<head>
	<title>Cycle Tracks Portal - Administrator's Page</title>
		<style type="text/css" media="all">@import "images/style.css";
</style>
	<link rel="alternate" type="application/rss+xml" title="RSS 2.0" href="rss/" />
</head>

<body>
<div class="content">
	<div class="topmenu">
		<div class="date_"><? echo date('l dS \of F Y'); ?></div>
	</div>
	
	<div id="submenu">
	</div>
		
	<div class="cycle">
		<div class="title" style="text-align: center; width: 179px">
			<sup>
			<span class="copynresv">©</span></sup>CYCLE TRACKS<sup><span class="copynresv">®</span></sup></div>
		<div class="slogan" style="width: 223px; height: 11px">&quot;We are ONE of the BEST and NOT like the REST!</div>
	</div>
	
	<div class="nav">
		<ul>
			<li><a href="#">HOME</a> | </li> 
			<li><a href="#">INSTRUCTIONS</a> | </li>
			<li><a href="#">FIND</a> | </li> 
			<li><a href="#">DISPLAY</a> | </li>
			<li><a href="#">ADMIN</a> | </li>
			<li><a href="#">CREDITS</a></li>
		</ul>
	</div>
	<br>
	</br>
	<table style="width: 764px; height: 141px;"align="center" cellspacing="1">
		<tr>
			<td>
			<form name="adminInput" action="admin.php" method="post" style="height: 99px">
			<table style="width: 284px; height: 56px" align="center">
				<tr>
					<td style="width: 189px; height: 21px;" class="uspstyle">Username</td>
					<td style="width: 191px; height: 21px;">
						<input type="text" name="username" size="30"/>
					</td>
				</tr>
				<tr>
					<td style="width: 189px; height: 21px;" class="uspstyle">Password</td>
					<td style="width: 191px; height: 21px;">
					<input type="password" name="password" size="30"/>
					</td>
				</tr>
				<tr>
					<td style="width: 189px; height: 36px;" class="uspstyle"></td>
					<td style="width: 191px; height: 36px;">
					<table style="width: 100%">
						<tr>
							<td style="width: 89px">
							<input type="submit" name="submit" value="Login" class="uspstyle2" style="height: 23px; width: 88px"/></td>
							<td style="width: 89px">
							<input type="reset" name="reset" value="Clear" class="uspstyle2" style="height: 23px; width: 88px"/></td>
						</tr>
					</table>
					</td>
				</tr>
			</table>
			</form>
				<?php
				if (!empty($errors)) { // Print any error messages.
					echo '<h1 class="errorLog1">Error!</h1>
					<p class="errorLog2">The following error(s) occurred:<br />';
					foreach ($errors as $msg) { // Print each error.
						echo " - $msg<br />\n";
					}
					echo '</p><p class="errorLog3">Please try again.</p>';
				}
				?>
			</td>
		</tr>
	</table>
	<div class="footer">
		<div class="padding">
			&copy; Copyright Cycle Tracks <span>®</span></div>
	</div>
	
	
</div>

</body>
</html>
<?php
ob_end_flush();
?>

I used the ob flush(), What happened was.....

1. I modified the code as posted by you.
2. 2 error msg appears on the admin.php, they are,

Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at C:\xampp\htdocs\cycle\admin.php:1) in C:\xampp\htdocs\cycle\admin.php on line 7

Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at C:\xampp\htdocs\cycle\admin.php:1) in C:\xampp\htdocs\cycle\admin.php on line 7

3. Then I entered the username and password.
4. Still remain in admin.php but with ONLY 1 error left(remember I was not redirected), it was,

Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at C:\xampp\htdocs\cycle\admin.php:1) in C:\xampp\htdocs\cycle\admin.php on line 7

5. Then I entered the username and password again.
6. I was sucessfully redirected to test2.php with the msg,

Array ( [user_id] => c13964 [first_name] => Dr. ).

Advise me.

dang.. There is a blank space on line 7. Remove it and try again.

Edit: Remove all the blank spaces.

All the blank spaces removed. The same problem occurred as in post 50.

I dont see any html tag or an echo statement above session_start. I cant see why it isn't working. ob_start isn't working either. I don't know. We need to wait for someone else to see where the error is or you have to break down your code and start debugging part by part.

I know this is a situation where we have reached the limit. Any how thanks for your valuable guidance and helps all along till here. I very much thank you for your contribution to solve my problems. I will follow your advise by breaking down the codes and debug them. If you have any solution in the future, kindly post it here as I will be watching over this thread till it solve whether by you, someone or myself. Thank you again.

No probs man.. But the sad thing is, the problem has not been solved. Anyways, break down the code and debug them. All the best..

Cheers,
Naveen

"In world of programming, we can make anything working, we rule the program and don't let the program rule us". ---- lordx78, Thank you and hope to get/post a solution here.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.