Page 1 of 3

Having problems with sessions

Posted: Fri Oct 06, 2006 3:43 am
by Stephen Bungert
I making a basic log in system using a flat file, I know it's not the most secure way so please don't tell me I should being using a db, I'm just trying to learn to use sessions ;-)

The first code lines i have start the session and register to session vars

Code: Select all

// Start Session
	session_start();
	session_register('useNam');
	session_register('pasWor');

I then display a form for users to enter the username and password. This gets sent pack to self and the submitted user name and password arechecked against the usernames in the file.

This works ok. Then the user gets redirected to a second page after logging in.

My problem is I don't seem to be able to access the session variables in the next page. All the tutorials I find say all you have to do is start the session in the next page to continue it but this doesn't seem too work.

Can anyone help me understand sessions?

Posted: Fri Oct 06, 2006 3:52 am
by Oren

Posted: Fri Oct 06, 2006 4:11 am
by Stephen Bungert
Thanks for the help, I changed to using the $_SESSIONS super global but it still doesn't work.

Code: Select all

<?php
	// Start Session
	session_start();
	
	// *** Constants & Variables ***
	// -----------------------------
	
	// URLs
	define("FILE_NAME",		'users.xml');
	define("REMOTE_URL",	'some url' . FILE_NAME);
	define("LOCAL_URL",		some url' . FILE_NAME);
	
	// Formatting
	define("N_LINE",	"\n");
	
	// CMS Specific
	define("PATH_NAME",			'roman');
	define("FULL_NAME",			'Roman Krall');
	define("WWW_NAME",			'www.romankrall.de');
	define("CMS_NAME",			'CMS');
	define("DISPLAY_NAME",		FULL_NAME . " - " . CMS_NAME);
	
	define("RESULT1", "username_error");
	define("RESULT2", "password_error");
	define("RESULT3", "username_password_error");
	define("RESULT4", "username_and_password_do_not_match_error");
	define("RESULT5", "login_successful");
	
	$self	= $_SERVER['PHP_SELF'];
	$action = undefined;
	
	$_SESSION['useNam'] = undefined;
	$_SESSION['pasWor'] = undefined;
	
	// XML
	$userCount	= 0;
	$userData	= array();
	
	$currentTag			= '';
	$xmlElementValues	= '';
	$unFound			= -1;
	$pwFound			= -1;
	$action		= RESULT0;
	
	$xmlParser	= NULL;
	$userFile	= NULL;
	
	// *** Arrays
	$xmlElements	= array();
	$xmlElements[0]	= 'username';
	$xmlElements[1]	= 'password';
	
	
	// User Name and Password
	if (empty($_POST['username']))
	{
		$_SESSION['useNam'] = "no_un";
	}
	else
	{
		$_SESSION['useNam'] = $_POST['username'];
	}
	
	if (empty($_POST['password']))
	{
		$_SESSION['pasWor'] = "no_pw";
	}
	else
	{
		$_SESSION['pasWor'] = $_POST['password'];
	}
	
	// *** Pre-Function Code ***
	// -------------------------
	
	// Check if un and pw have already been submitted
	if ($_SESSION['useNam'] != "no_un" && $_SESSION['pasWor'] != "no_pw")
	{
		$action = "check_user";
	}
	else
	{
		$action = undefined;
	}
	
	// *** Functions ***
	// -----------------
	
	// HTML
	
	function htmlStart()
	{
		echo "<html>" . N_LINE;
	}
	
	function headStartEnd($title)
	{
		echo "	<head>" . N_LINE;
		echo "	<title>$title</title>" . N_LINE;
		echo "	" . N_LINE;
		echo "	<meta http-equiv='content-type'			content='text/html; charset=utf-8'>" . N_LINE;
		echo "	<meta http-equiv='imagetoolbar'			content='false'>" . N_LINE;
		echo "	<meta name='MSSmartTagsPreventParsing'	content='true'>" . N_LINE;
		echo "	" . N_LINE;
		echo "	<link href='../css/cms_" . PATH_NAME . ".css' rel='stylesheet' type='text/css'>" . N_LINE;
		echo "	" . N_LINE;
		echo "	<script language='javascript' src='../javascript/cms_" . PATH_NAME . "_login.js'></script>" . N_LINE;
		echo "	</head>" . N_LINE;
		echo "	" . N_LINE;
	}
	
	function bodyStart($jsReq)
	{
		if ($jsReq == undefined)
		{
			echo "	<body onload=\"setVars()\">" . N_LINE;
		}
		else
		{
			echo "	<body>" . N_LINE;
		}
	}
	
	function bodyTitle()
	{
		echo "		<h1>" . DISPLAY_NAME . " Login</h1>" . N_LINE;
	}
	
	function bodyError($errMsg)
	{
		echo "		<p class='centre'><span class='textProblem'>$errMsg</span></p>" . N_LINE;
	}
	
	function loginForm($actionValue, $webUrl)
	{
		echo "		<form name='loginForm' method='post' action='" . $actionValue . '' . "' onsubmit='return login()' onreset='clearLogin()'>" . N_LINE;
		echo <<< formEnds
			<table class="noBorder" border="0" align="center" cellpadding="4" cellspacing="2">
				<tbody>
					<tr align="left" valign="top" class="rowColourLogin">
						<td align="center" valign="middle">
							<br><a href="http://${webUrl}/"><img alt="$webUrl" title="$webUrl" border="0" class="border" src="../images/brand.png" width="110" height="110"></a>
							<br><br><br></td>
					</tr>
					<tr align="left" valign="top">
						<td align="center">
							<table border="0" align="center" cellpadding="4" cellspacing="0" class="noBorder">
								<tbody>
									<tr align="center" valign="top">
										<td><span class="label"><span class="textNormal" id="usernameNoProblem">Benutzername:</span><span class="textHidden" id="usernameProblem">Benutzername erforderlich:</span></span><br>
										<input value="test" maxlength="20" class="styled" name="username" type="text" id="username" size="20" onblur="resetClassName(this)"></td></tr>
									<tr align="center" valign="top">
										<td><span class="label"><span class="textNormal" id="passwordNoProblem">Kennwort:</span><span class="textHidden" id="passwordProblem">Kennwort erforderlich:</span></span><br>
										<input value="test" maxlength="20" class="styled" name="password" type="password" id="password" size="20" onblur="resetClassName(this)"></td></tr>
								</tbody>
						  </table>
						    <p>
				              <input name="submit" value="Einloggen" type="submit" id="submitButton">
				              <input name="reset" value="Zur&uuml;cksetzen" type="reset" id="clearButton">
		                  </p>
					    </td>
					</tr>
				</tbody>
			</table>
		</form>
formEnds;
	}
	
	function loginPicture($webUrl)
	{
		echo <<< tableEnds
			<table class="noBorder" border="0" align="center" cellpadding="4" cellspacing="2">
				<tbody>
					<tr align="left" valign="top" class="rowColourLogin">
						<td align="center" valign="middle">
							<br><a href="http://${webUrl}/"><img alt="$webUrl" title="$webUrl" border="0" class="border" src="../images/brand.png" width="110" height="110"></a>
							<br><br><br></td>
					</tr>
				</tbody>
			</table>
tableEnds;
	}
	
	function bodyEnd()
	{
		echo N_LINE . "		<br><br><br><br>" . N_LINE . "		<p class='credit'>CMS System wurde gestaltet von <a href='http://www.bungert.co.uk/'>bungert.co.uk</a></p>" . N_LINE;
		echo "	</body>" . N_LINE;
	}
	
	function htmlEnd()
	{
		echo '</html>';
	}
	
	// Look for a matching $_SESSION['useNam'] and $_SESSION['pasWor'] in the users file
	function checkForValidCredentials($userCount, $userData, $unFound, $pwFound, $action, $xmlElements)
	{
		for ($index = 0; $index < $userCount; $index ++)
		{
			if ($userData[$index][$xmlElements[0]] == $_SESSION['useNam'])
			{
				$unFound = $index;
				break;
			}
			else
			{
				// Keep looking...
			}
		}
	
		for ($index = 0; $index < $userCount; $index ++)
		{
			if ($userData[$index][$xmlElements[1]] == $_SESSION['pasWor'])
			{
				$pwFound = $index;
				break;
			}
			else
			{
				// Keep looking...
			}
		}
		
		if ($unFound < 0 && $pwFound >= 0 && $_SESSION['useNam'] != 'no_un' && $_SESSION['pasWor'] != 'no_pw')		// $_SESSION['useNam'] error
		{
			$action = RESULT1;
		}
		else if ($pwFound < 0 && $unFound >= 0 && $_SESSION['useNam'] != 'no_un' && $_SESSION['pasWor'] != 'no_pw')	// $_SESSION['pasWor'] error
		{	
			$action = RESULT2;
		}
		else if ($unFound < 0 && $pwFound < 0 && $_SESSION['useNam'] != 'no_un' && $_SESSION['pasWor'] != 'no_pw')	// $_SESSION['useNam'] and $_SESSION['pasWor'] error
		{	
			$action = RESULT3;
		}
		else if ($unFound == $pwFound && $_SESSION['useNam'] != 'no_un' && $_SESSION['pasWor'] != 'no_pw')			// Login ok
		{
			$action = RESULT5;
		}
		else if ($unFound != $pwFound && $_SESSION['useNam'] != 'no_un' && $_SESSION['pasWor'] != 'no_pw')			// $_SESSION['useNam'] and $_SESSION['pasWor'] are found but don't match
		{
			$action = RESULT4;
		}
		else																				// Bypassed login page
		{
			$action = undefined;
		}
		
		return $action;
	}
	
	// *** XML Parsing
	
	// *** Callback functions
	function startElementHandler($parser, $elementName)
	{
		global $currentTag;
		
		$currentTag = $elementName;
	}
	
	function endElementHandler($parser, $elementName)
	{
		global $currentTag;
		global $userCount;
		
		$currentTag = '';
		
		if ($elementName == "USER")
		{
			$userCount++;
		}
	}
	
	function userDataHandler($parser, $data)
	{
		global $userCount;
		global $userData;
		global $currentTag;
		global $xmlElements;
		
		// Return if $currentTag is empty
		if ($currentTag == '')
		{
			return;
		}
		
		// Otherwise put data in the array for later use
		if ($currentTag == "USERNAME")
		{
			$userData[$userCount][$xmlElements[0]] = $data;
		}
		
		if ($currentTag == "PASSWORD")
		{
			$userData[$userCount][$xmlElements[1]] = $data;
		}
	}
	
	// Create XML parser
	function openParser()
	{
		global $xmlParser;
		
		$xmlParser = xml_parser_create();
		
		if (!$xmlParser)
		{
			die ("Error: Couldn't create XML Parser.");
		}
	}
	
	// Open the user file
	function openXmlFile()
	{
		global $userFile;
		
		$userFile = fopen(LOCAL_URL, FILEMODE);
		
		if (!$userFile)
		{
			die ("Error: Couldn't open the Users file - '" . FILE_NAME . "'doesn't exist in:" . LOCAL_URL);
		}
	}
	
	// Read the Termine file
	function parseXmlFile()
	{
		global $xmlParser;
		global $userFile;
		
		xml_set_element_handler($xmlParser, "startElementHandler", "endElementHandler");
		xml_set_character_data_handler($xmlParser, "userDataHandler");
		
		while ($data = fread($userFile, 4096))
		{
			if (!xml_parse($xmlParser, $data, feof($userFile)))
			{
				break; // Get out of while loop when finished with the file
			}
		}
	}
	
	// Free the parser
	function closeParser()
	{
		global $xmlParser;
		
		xml_parser_free($xmlParser);
	}
	
	// Close the opened file
	
	function closeXmlFile()
	{
		global $userFile;
		
		fclose($userFile);
	}
	
	
	
	// *** Post-Function Code ***
	// --------------------------
	
	// Open and parse the Users file
	openXmlFile();
	openParser();
	parseXmlFile();
	closeParser();
	closeXmlFile();
	
	htmlStart();
		headStartEnd(DISPLAY_NAME . " Login");
		
			bodyStart($action);
				bodyTitle();
				
				if ($action == "check_user")
				{
					$action = checkForValidCredentials($userCount, $userData, $unFound, $pwFound, $action, $xmlElements);
				}
				
				if ($action == RESULT1) // Username Error, Password was OK
				{
					loginForm($self, WWW_NAME);
					bodyError("The Username you submitted was incorrect. Please try again.");
				}
				else if ($action == RESULT2) // Password Error, Username was OK
				{
					loginForm($self, WWW_NAME);
					bodyError("The Password you submitted was incorrect. Please try again.");
				}
				else if ($action == RESULT3) // Username & Password Error, both were wrong
				{
					loginForm($self, WWW_NAME);
					bodyError("The Username and Password you submitted were incorrect. Please try again.");
				}
				else if ($action == RESULT4) // Username and Password do not match Error
				{
					// Same message as above. The username and password exist but they don't match,
					// they are from different users. This could be explained in a seperate message
					loginForm($self, WWW_NAME);
					bodyError("The Username and Password you submitted were incorrect. Please try again.");
				}
				else if ($action == RESULT5) // Logged in OK
				{
					loginPicture(WWW_NAME);
					echo "<p class='centre'>You have logged in successfully as <b>" . $_SESSION['useNam'] . ".</b><br><a href=\"http://localhost/roman/updater/php/termine.php\">Please wait...</a></p>";
					echo "<script language=\"javascript\" type=\"text/javascript\">";
					echo "	var timer = setTimeout('redirectURL(\"http://localhost/roman/updater/php/termine.php\")',3000);";
					echo "</script>";
				}
				else
				{
					loginForm($self, WWW_NAME);
				}
				
			bodyEnd();
	htmlEnd();
?>
Above is my main page, and below is the test second page:

Code: Select all

<?php
	
	session_start();

	echo "Username is: " . $_SESSION['useNam'] . "<br>"; 
	
	
?>
The echo above doesn't show anything.

I must be doing something wrong but I don't know what.

Posted: Fri Oct 06, 2006 4:24 am
by RobertGonzalez
You have a syntax error in your code.

Code: Select all

define("LOCAL_URL",          some url' . FILE_NAME);
Should be

Code: Select all

define("LOCAL_URL",          'some url' . FILE_NAME);

Posted: Fri Oct 06, 2006 4:39 am
by Stephen Bungert
Thanks, got that. Still same problem.

I just can't understand how to get these sessions working. Anyone have any ideas?

Posted: Fri Oct 06, 2006 4:48 am
by RobertGonzalez
Before trying them out on a large app, try something small...

page1.php

Code: Select all

<?php
session_start();
$_SESSION['testvar'] = 'This is a session var';
?>
<html>
<head></head>
<body>
<a href="page2.php">Click here to go to the next page</a>
</body>
page2.php

Code: Select all

<?php
session_start();
if (isset($_SESSION['testvar']))
{
    $sessvar = $_SESSION['testvar'];
}
else
{
    $sessvar = 'There was a big fat error.';
}
?>
<html>
<head></head>
<body>
Session results: <?php echo $sessvar; ?>
</body>
See if this works.

Posted: Fri Oct 06, 2006 5:18 am
by Stephen Bungert
I get the else error message when I try your test pages!

Posted: Fri Oct 06, 2006 5:55 am
by patrikG
Stephen Bungert wrote:I get the else error message when I try your test pages!
Please be more specific and post the exact error-message.

Posted: Fri Oct 06, 2006 9:10 am
by Stephen Bungert
'There was a big fat error.';


As in page 2 provided by Everah

Posted: Fri Oct 06, 2006 9:17 am
by patrikG
:lol:
have you switched on error reporting?

Posted: Fri Oct 06, 2006 9:23 am
by Stephen Bungert
I've included this in the sample pages that I was told to try:

Code: Select all

error_reporting(E_ALL);
but still nothing apart from what was in the else echo.

Posted: Fri Oct 06, 2006 10:39 am
by RobertGonzalez
Your system is not handling sessions. Before you do anything else, can you execute this code (as its own PHP page) and copy and paste the results back exactly as they appear on the screen?


Run the following in a new file and tell us the results please.

Code: Select all

<?php

$neg = array(0, false, '', null, 'off');
$ve = phpversion();
$os = PHP_OS;
$er = intval(error_reporting());
$rg = (in_array(strtolower(ini_get('register_globals')), $neg) ? 'Off' : 'On');
$de = (in_array(strtolower(ini_get('display_errors')), $neg) ? 'Off' : 'On');
$so = (in_array(strtolower(ini_get('short_open_tag')), $neg) ? 'Off' : 'On');
$le = '';
$cli = (php_sapi_name() == 'cli');
$eol = ($cli ? "\n" : "<br />\n");

$gle = get_loaded_extensions();
$rows = array();
$wide = 4;
$j = count($gle);
$pad = $wide - $j % $wide;
$len = max(array_map('strlen', $gle));
$func = create_function('$a', 'return str_pad($a, ' . intval($len) . ');');
$gle = array_map($func, $gle);
for($i = 0; $i < $j; $i += $wide)
{
    $le .= '   ' . implode('   ', array_slice($gle, $i, $wide)) . "\n";
}
if ($cli)
{
     $le = $eol . $le;
}
else
{
 $le = '<pre>' . $le . '</pre>';
}

$ec = array(
   'E_STRICT' => 2048, 'E_ALL' => 2047, 'E_USER_NOTICE' => 1024,
   'E_USER_WARNING' => 512, 'E_USER_ERROR' => 256, 'E_COMPILE_WARNING' => 128,
   'E_COMPILE_ERROR' => 64, 'E_CORE_WARNING' => 32, 'E_CORE_ERROR' => 16,
   'E_NOTICE' => 8, 'E_PARSE' => 4, 'E_WARNING' => 2, 'E_ERROR' => 1,
);

$e = array();
$t = $er;
foreach ($ec as $n => $v)
{
   if (($t & $v) == $v)
   {
      $e[] = $n;
      $t ^= $v;
   }
}
$er = $er . ' (' . implode(' | ', $e) . ')';

if (!$cli)
{
  echo '<html><head><title>quick info</title></head><body>' . "\n";
}

echo 'PHP Version: ' . $ve . $eol;
echo 'PHP OS: ' . $os . $eol;
echo 'Error Reporting: ' . $er . $eol;
echo 'Register Globals: ' . $rg . $eol;
echo 'Short Tags: ' . $so . $eol;
echo 'Display Errors: ' . $de . $eol;
echo 'Loaded Extensions:' . $le . $eol;

if (!$cli)
{
  echo '</body></html>' . "\n";
}

?>

Posted: Fri Oct 06, 2006 11:00 am
by impulse()
Are you accessing your pages through an online web proxy?

Posted: Fri Oct 06, 2006 2:55 pm
by Stephen Bungert
Here's what I see in the browser:

PHP Version: 5.0.5
PHP OS: WINNT
Error Reporting: 2039 (E_USER_NOTICE | E_USER_WARNING | E_USER_ERROR | E_COMPILE_WARNING | E_COMPILE_ERROR | E_CORE_WARNING | E_CORE_ERROR | E_PARSE | E_WARNING | E_ERROR)
Register Globals: On
Short Tags: On
Display Errors: Off
Loaded Extensions:
bcmath calendar com_dotnet ctype
ftp iconv odbc pcre
session SPL SQLite standard
tokenizer zlib libxml dom
SimpleXML wddx xml apache2handler
gd mbstring mysql mysqli


I'm running apache 2. something on windows xp. I have perl and php installed. I have php sites that work, but now I want to use sessions and they don't seem to work.

Posted: Fri Oct 06, 2006 2:57 pm
by Stephen Bungert
No proxy