The first thing at the start of every page is "session_start()". Next, each page has the following code. The 'loggedIn' session variable was initialized to 0 with a require_once call of another script. When you log in, the page that did the check will show the login is successful, but navigate to any other page (even reload the current one) and you're no longer logged in. What's missing?

if (isset($_POST['usernameField']) && isset($_POST['passwordField']) && ($_SESSION['loggedIn']==0)){
	if (!empty($_POST['usernameField']) && !empty($_POST['passwordField'])){

		//Connect to the MySQL database server
		$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die('Error connecting to database');
	
		//Connect to the specified database
		mysql_select_db($dbname);


		$sql = sprintf("SELECT FirstName FROM tblCustomers WHERE UserName = '%s' AND Password = md5('%s')", 
			mysql_real_escape_string($_POST['usernameField']),
			mysql_real_escape_string($_POST['passwordField']));

		$result = mysql_query($sql);

		if ($row = mysql_fetch_array($result)){			
			session_start();
			session_register($_POST['usernameField']);
			$_SESSION['loggedIn'] = 1;
			$_SESSION['Name'] = $row['FirstName'];
		}else{
			$_SESSION['loggedIn'] = 0;
			$_SESSION['Name'] = '';
		}

		unset($_POST['usernameField']);
		unset($_POST['passwordField']);
	}

}

Recommended Answers

All 3 Replies

when loading a page, the $_POST fields may be empty, so the code is not executed.

Do you use:

if (! session_id())
    session_start();

at the top of every page ? Or something else perhaps ?

I have session_start() at the beginning, and $_POST fields don't need to be filled out.

User logs in, the page reloads and $_SESSION will output 1, showing that the user did indeed login. If I then refresh the page or go to another, the session variable is no longer set.

when loading a page, the $_POST fields may be empty, so the code is not executed.

like the user said, if the POST variables aren't set, the code won't execute. Even if they are, the code won't execute the second time around if the user was validated on the first run, because your third condition ($_SESSION==0) would be set to '1'.

On subsequent pages, you should first start a session, then check if the loggedIn variable is set correctly. Something like this:

session_start();
if($_SESSION['loggedIn'] == 1)
{
	print $_SESSION['Name'] . ' is logged in!';
}
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.