Having to login twice to access page?

This has been an ongoing issue from the start.

When I try to login I enter the username and password and click login, then get taken back to the login page to reenter the same details and the second time I click login I get logged in. Now if I then log out and close window and wait a few seconds, restart again and try to log in, I get in first time. I believe this could be a session issue but I thought unsetting the unset($_SESSION[‘admin’]); would cause the session to be lost and have to start again.

Why ?

I have a redirect to originating page, so if I was to view a previous page within the admin area I have to log in and then once loggeed in it will redirect to the page I was on before.

Here are my completely scripts.

adminCreateCampaign.php

<?php
session_set_cookie_params(0, '/', '.****.com'); session_start(); error_reporting(-1);

define('site_title', 'Admin ');
define('pageTitle', 'Admin ');
$_SESSION['loginRedirect'] = "adminCreateCampaign.php";

include("functions-for-email.php");

$checkAdminStatus = checkAdminStatus($mysqli);
  if(!isset($_SESSION['admin']) || $checkAdminStatus == "NOACCESS") {
    $_SESSION['error'] = 'You must be logged in to view that page. (el.S1)';
	//$_SESSION['loginRedirect'] = "showStats.php";
//echo("You must be logged in to view that page. (el.S1)<br>"); exit;
    @mysqli_close($mysqli);
	header('Location: ' . adminFullWebAddress . '/index.php'); exit;
  } else {
    if($_SESSION['admin']['account_type'] != 'admin') {
      $_SESSION['error'] = 'You do not have the priviledges to view that page. (el.S2)';
      @mysqli_close($mysqli);
	  header('Location: ' . adminFullWebAddress . '/index.php'); exit;
    }
  }
?>
<!DOCTYPE>
<html>
<head>
<link href="adminstyle.css" rel="stylesheet" type="text/css" />
<title><?php echo(site_title); ?></title>
</head>
<body>
	<div id="container">

								<div class="containerInner">
								<div id="leftInner100">
								<?php // start of leftInner ?>

<?php menu(); ?>

					<h1 class="middleTitle">Admin </h1>
					<?php
					if(isset($thisError)) { echo '<div class="errorDiv">',$thisError,'</div>'; unset($thisError); }
					if(isset($thisSuccess)) { echo '<div class="successDiv">',$thisSuccess,'</div>'; unset($thisSuccess); }
					?>







					
					<br><br>
								</div><?php //	end of leftInner ?>
								</div><?php // end of containerInner ?>

		<div class="clearfix"></div>

	</div><?php // container ?>
</body>
</html>
<?php @mysqli_close($mysqli); ?>

index.php

<?php
session_set_cookie_params(0, '/', '.****.com'); session_start(); error_reporting(-1);
include("functions.php");
$checkAdminStatus = checkAdminStatus($mysqli);
//$_SESSION['loginRedirect'] = adminFullWebAddress . "/index.php";
$fromlink4 = isset($_SERVER['REMOTE_ADDR']) ? (gethostbyaddr($_SERVER['REMOTE_ADDR'])) : "empty";
$ipAddress = $_SERVER['REMOTE_ADDR'];

	if(isset($_POST['email'])) { $email = $_POST['email']; $email = strip_tags($email); } else { $email = ""; }
	if(isset($_POST['pass'])) { $password = $_POST['pass']; $pass = $_POST['pass']; } else { $pass = ""; }
	if(isset($_POST['login']) && trim($_POST['login']) == 'Login') {
			$checkEmail		= db_query($mysqli, "SELECT `adminid` FROM `admins` WHERE `email` = '" . $mysqli->real_escape_string($email) . "' LIMIT 1");
			$checkBanned	= db_query($mysqli, "SELECT `adminid` FROM `admins` WHERE `email` = '" . $mysqli->real_escape_string($email) . "' AND `suspended` = 'Yes' LIMIT 1");
			$failedLoginCounter	= 0;

			if(!$email) {
				$thisError = 'Please enter your e-mail address.';
			} else if(! $checkEmail->num_rows) {
				$thisError = 'Either the email address, password or both were not entered correctly.';
			} else if(!$password) {
				$thisError = 'Please enter your password.';
			} else if($checkBanned->num_rows) {
				$thisError = 'Your account has been suspended by Admin.';
			} else {
					$password = md5($password);
					$checkAccount = db_query($mysqli, "SELECT * FROM `admins` WHERE `email` = '" . $mysqli->real_escape_string($email) . "' AND `password` = '" . $mysqli->real_escape_string($password) . "' LIMIT 1");
						if($checkAccount->num_rows) {
						$saveChanges = db_query($mysqli, "UPDATE `admins` SET `lastlogindatetime` = '" . $mysqli->real_escape_string(datetimenow) . "', `lastAccessSinceLogin` = '" . $mysqli->real_escape_string(datetimenow) . "', `lastloginip` = '" . $mysqli->real_escape_string($ipAddress) . "', `failedLoginCounter` = 0 WHERE `email` = '" . $mysqli->real_escape_string($email) . "' LIMIT 1");
						// set lastlogindatetime
						$_SESSION['admin'] = $checkAccount->fetch_assoc();
						$loginRedirect = isset($_SESSION['loginRedirect']) ? $_SESSION['loginRedirect'] : "";
						$_SESSION['success'] = 'You are now logged in. (ok.L2) ' . $loginRedirect;
							  header('Location: ' . adminFullWebAddress . '/' . $loginRedirect); exit;
						} else {
								$thisError = 'Your e-mail address and/or password is incorrect.<br>If you still face issues, you can <a href="startresetpw.php">reset your password</a>';
								$saveChanges = db_query($mysqli, "UPDATE `admins` SET `failedLoginCounter` = `failedLoginCounter` + 1, `lastloginfailedip` = '" . $mysqli->real_escape_string($ipAddress) . "', `lastlogindatetimeFailed` = '" . $mysqli->real_escape_string(datetimenow) . "' WHERE `email` = '" . $mysqli->real_escape_string($email) . "' LIMIT 1"); // set lastlogindatetimeFailed
								 }
    				}
	}
if(!isset($_SESSION['admin'])) {
define('site_title', 'Login');
define('pageTitle', 'Login');
} else {
define('site_title', 'Home');
define('pageTitle', 'Home');
}
?>
<!DOCTYPE>
<html>
<head>
<link href="adminstyle.css" rel="stylesheet" type="text/css" />
<title><?php echo(site_title); ?></title>
</head>
<body>
	<div id="container">
			<div class="containerInner">
			<div id="leftInner100">
			<?php // start of leftInner ?>

				<div id="mainphoto"><?php //specialMessage($mysqli); mainPageImage(""); ?></div>
				<div class="clear"></div><?php

					if(isset($_SESSION['admin'])) {
						menu();
					}

					if(isset($thisError)) { echo '<div class="errorDiv">',$thisError,'</div>'; }
					if(isset($thisSuccess)) { echo '<div class="successDiv">',$thisSuccess,'</div>'; }
					unset($thisError); unset($thisSuccess);

						if(!isset($_SESSION['admin'])) { ?>
								<div style="width: 100%; margin: 0em auto; text-align: center;">
									<form method="POST" action="index.php" style="width: 15em; text-align: center;">
									  <div class="field"> E-mail Address </div>
									  <div class="value"> <input type="text" name="email" value="<?php if(isset($_POST['email'])) { echo $email; } ?>" style="width: 12.5em;" title="email"> </div>
										  <div class="field"> Password<br><span style="font-size: 0.8em;"><?php
										  if (isset($_POST['pass'])) { echo('<strong style="color: red;">'); } ?>(Please note: your password may be CaSe SeNSitIvE)<?php if (isset($_POST['pass'])) { echo('</strong>'); } ?></span>
										  </div>
									  <div class="value"> <input type="password" name="pass" value="" style="width: 12.5em;" title="pass"> </div>
									  <div><br><input type="submit" name="login" value="Login"> <input type="reset" value="Clear"><br></div>
									</form><br>
								  <div class="clearFloat"></div>
								</div>
						<?php
						} else { ?>logged in<?php } ?>

			<br><br>
			</div><?php //	end of leftInner ?>
			</div><?php // end of containerInner ?>
		<div class="clearfix"></div>
	</div><?php // container ?>
</body>
</html>
<?php
@mysqli_close($mysqli); ?>

functions.php

<?php
define('showOutput', 0);

include("/home/****/db_login_functions.php");
define('db_table_name', 'clientList');
define('mailHost', 'mail.****.com');
define('mailUsername', '[email protected]****.com');
define('mailPW', '****');

define('bounce', '[email protected]****.com');

define('fullDomain', 'https://www.admin.****.com');
define('adminFullWebAddress', 'https://www.admin.****.com');
define('adminEmail', '[email protected]****.com');
define('fromEmail', '[email protected]****.com');
define('fromName', 'DO NOT REPLY');
define('REMOTEADDR', isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '');
define('PHPSELF', $_SERVER['PHP_SELF']);
define('HTTPREFERER', isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : "not set");

define('unsub', 'https://www.****.com/unsub.php'); define('securityhash', 'abc'); // NEVER change this securityhash.

date_default_timezone_set('Europe/London');
define('datetimenow', date("Y-m-d H:i:s"));

/*		check if user is allowed to access a certain page or not.	*/
function checkAdminStatus($mysqli) { $yesNo = "";

	if(isset($_GET['action']) && $_GET['action'] == 'logout') {
		unset($_SESSION['admin']);
		$_SESSION['success'] = 'You have successfully logged out. (lo.1)';
 	   header('Location: index.php'); exit;
	}
	if(isset($_SESSION['admin']) ) {
		//			need to add in code to check if logged in for more than 1 hour, if so log out on next refresh of page.
		if ($_SESSION['admin']['lastAccessSinceLogin'] < date( 'Y-m-d H:i:s', strtotime("-5 minutes") )) {		unset($_SESSION['admin']);
		$_SESSION['error'] = 'You were logged out due to no activity, please login again to view that page. (lo.2)';
		header('Location: index.php'); exit;
		}
	$checkBanned	= db_query($mysqli, "SELECT `adminid` FROM `admins` WHERE `email` = '" . $mysqli->real_escape_string($_SESSION['admin']['email']) . "' AND `suspended` = 'Yes' LIMIT 1");
		if($checkBanned->num_rows) {		$yesNo = "NOACCESS";		//$_SESSION['error'] = 'You must be logged in to view that page.';
		} else {		$yesNo = "ACCESS";		// if logged in, update		`users`.`lastAccessSinceLogin`		with current datetime.
		$updateLastAccessSinceLogin = db_query($mysqli, "UPDATE `admins` SET `lastAccessSinceLogin` = '" . $mysqli->real_escape_string(datetimenow) . "', `lastloginip` = '" . $mysqli->real_escape_string(REMOTEADDR) . "', `failedLoginCounter` = 0 WHERE `email` = '" . $mysqli->real_escape_string($_SESSION['admin']['email']) . "' LIMIT 1");
		$_SESSION['admin']['lastAccessSinceLogin'] = datetimenow;
		}
	}

return $yesNo;
}

function menu() {
echo('<a href="index.php?action=logout">Log Out</a>&nbsp;&nbsp;&nbsp;&nbsp;');
echo('
<a href="adminCreateCampaign.php">Create Campaign</a><br><br><br>');
}
?>

.htaccess (within the admin folder)

Header set Access-Control-Allow-Origin "*"

RewriteEngine On
RewriteCond %{HTTPS} off
# First rewrite to HTTPS:
# Don't put www. here. If it is already there it will be included, if not
# the subsequent rule will catch it.
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# Now, rewrite any request to the wrong domain to use www.
# [NC] is a case-insensitive match
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule .* https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

### DON'T DELETE!! Below entry is MUST for your PHP sites like wordpress,joomla and etc to work properly.
suPHP_ConfigPath /home/****/php.ini

.htaccess (within the root folder)

Header set Access-Control-Allow-Origin "*"

RewriteEngine On
RewriteCond %{HTTPS} off
# First rewrite to HTTPS:
# Don't put www. here. If it is already there it will be included, if not
# the subsequent rule will catch it.
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# Now, rewrite any request to the wrong domain to use www.
# [NC] is a case-insensitive match
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule .* https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

### DON'T DELETE!! Below entry is MUST for your PHP sites like wordpress,joomla and etc to work properly.
suPHP_ConfigPath /home/****/php.ini

the php.ini file

allow_url_fopen = on
allow_irl_include = on
date.timezone = Europe/London
safe_mode = off
upload_max_filesize = 20M
post_max_size = 20M
upload_tmp_dir = "/home/****/tmp"
session.save_path = "/home/****/sessions"
session.use_only_cookies = on
error_reporting = E_ALL
log_errors = On
display_errors = Off
track_errors = On
error_log = "/home/****/errors.log"
sendmail_from = "[email protected]****.com"

The problem is most likely the above two lines of code in the checkAdminStatus() function. When you login, redirect back to what ever page you were on, call checkAdminStatus(), the [‘lastAccessSinceLogin’] value is whatever it was in the database table at the time of login. The above code then logs you out, sets an error message, which you never access and display in the posted code for index.php to let you know what happened, then redirects to index.php again.

You have far too much code and redirecting around on your site. Some points -

  1. Logging in should only be about authenticating who the user is, not what permissions they have. When someone successfully logs in, the only piece of user information you should store in a session variable is the user’s id (auto-increment primary index.)
  2. Even if the only type of user you will have are administrators, the user information should be stored in a table named user(s) or similar, not in a table named admins.
  3. If a logged in user visits a page, you should query to get their current user information and current permissions, using the user’s id from the session variable, then use those current values throughout rest of the code on the page. This will allow any changes made to the user information/permissions to take effect immediately after the change is made, i.e. on the next page request.
  4. The only redirect you should have on a page is upon the successful completion of post method form processing code, without any errors, is to redirect to the url of the current page, to cause a get request for that page. Any navigation to other pages should be handled through navigation links on the page.
  5. Any function, except one who’s specific purpose is to redirect/exit, should return to the calling code.
  6. Any value you return from a function should be tested by the calling code to decide what to do as a result of calling the function.
  7. Any success/error messages you set in a (session) variable should be tested/used on a page.so that you will know what’s going on.
  8. You should validate all independent input values at one time, storing validation error messages in an array, so that a visitor doesn’t need to keep re-submitting a form for each error, i.e. don’t use else if() statements, except for validation steps that are dependent on the result of a previous validation step.
  9. Use php’s password_hash() and password_verify() for hashing/testing password values.

Of course, I did not see that until now. Multiple redirects.
All seems to be working now I have stopped it redirecting when not needed.
Thank you for your help on this.

Sponsor our Newsletter | Privacy Policy | Terms of Service