First login is not successful

Hi there!

This login scripts doesn`t work in first attempt but It works in seconds attempt!
What is the issue!?

<?php
session_start();
include("passwords.php");
if ($_POST["ac"]=="log") { /// do after login form is submitted
     if ($USERS[$_POST["username"]]==$_POST["password"]) { /// check if submitted username and password exist in $USERS array
          $_SESSION["logged"]=$_POST["username"];
     } else {
          echo 'Incorrect username/password. Please, try again.';
     };
};
if (array_key_exists($_SESSION["logged"],$USERS)) { //// check if user is logged or not
     header("Location: http://cdn.otoraby.com/index.php"); // redirects
     die();
} else { //// if not logged show login form
     echo "<b>Please login to CDN</b><br>";
     echo '<form action="login.php" method="post"><input type="hidden" name="ac" value="log"> ';
     echo 'Username: <input type="text" name="username" />';
     echo 'Password: <input type="password" name="password" />';
     echo '<input type="submit" value="Login" />';
     echo '</form>';
};
?>

put some echoes in there to see how the flow goes, and to check the values of the variables

I don’t see any <html> in your code but the fact that you are echoing leads me to believe that you are using this code within <html>. Try to avoid this. Make sure session_start(); is called before headers are sent to the browser meaning ANYTHING sent to browser <html> tags etc. You also can do your header(location) if match is found on post. It’s a good idea to check for the array key before using it to compare to post password. I won’t get into non-encrypted passwords… Bad practice.

<?php
session_start();
include("passwords.php");
if ($_POST["ac"]=="log") { /// do after login form is submitted
	if(array_key_exists($_POST['username'],$USERS) && $USERS[$_POST['username']]==$_POST['password']) { /// check if submitted username and password exist in $USERS array
		$_SESSION["logged"]=$_POST["username"];
		header("Location: http://cdn.otoraby.com/index.php"); // redirects
		die();
     } else {
          echo 'Incorrect username/password. Please, try again.';
     }
}
if (array_key_exists($_SESSION["logged"],$USERS)) { //// check if user is logged or not
	header("Location: http://cdn.otoraby.com/index.php"); // redirects
	die();
} else { //// if not logged show login form
     echo "<b>Please login to CDN</b><br>";
     echo '<form action="login.php" method="post"><input type="hidden" name="ac" value="log"> ';
     echo 'Username: <input type="text" name="username" />';
     echo 'Password: <input type="password" name="password" />';
     echo '<input type="submit" value="Login" />';
     echo '</form>';
}
?>

Without firing up the debugger, I think it’s this:


if (array_key_exists($_SESSION["logged"],$USERS)) { //// check if user is logged or not  

Try printing the logged session variaible on each page load (after session_start() to see if thats the issue