I'm trying to implement a PHP login script which works with 3 PHP files. The scripts work fine when using correct user names and passwords, and the script even blocks access when the wrong information is provided. My problem is that the script is allowing access when you press the submit button on the form and don't insert a user name or password.
The first script goes like this:
<form action="login2.php" method="post">
Usuario:<br />
<input type="text" name="username" class="formtext" />
Contraseña:<br />
<input type="password" name="password" class="formtext" />
<input type="submit" value="Ingresar" class="formbutton" />
</form>
As you can see, the form accesses "login2.php" which goes like this:
<?php
$usernames = array("user1", "user2", "user3", "superman");
$passwords = array("test", "pass2", "password3", "supermans password");
$page = "noticias.php";
for($i=0;$i<count($usernames);$i++){
$logindata[$usernames[$i]]=$passwords[$i];
}
if($logindata[$_POST["username"]]==$_POST["password"]){
session_start();
$_SESSION["username"]=$_POST["username"];
header('Location: '.$page);
exit;
}else{
header('Location: login.php?wrong=1');
exit;
}
?>
Finally, the page I'm trying to restrict access to has the following code added at the top to make sure the user is logged in:
<?php require("login3.php"); ?>
And "login3.php" has the following code:
<?php
session_start();
if(!isset($_SESSION['username'])){
header('Location: login.php');
exit;
}
?>
If anyone can help me out with this since I got these scripts from an online tutorial, and don't know much about PHP, and really need to know why access is being allowed with blank usernames and passwords.
if($logindata[$_POST["username"]]==$_POST["password"])
If $logindata[$_POST["username"]]
or in this case $logindata['']
is undefined, then PHP throws a notice error and returns NULL or something that's empty, which you then compare to $_POST['password']
which is also '' (or empty)
and (empty == empty)
returns true, with a notice error of course.
You just need to add a check to make sure the username exists as well, such as:
if(isset($logindata[$_POST["username"]]) && $logindata[$_POST["username"]]==$_POST["password"])
You problem is that if $_POST['username']
is empty, and you use that as an array key reference, PHP
will treat that null as a VALID+undefined
array reference, so your password check boils down to:
if ($loginData[null] == null)
which becomes
if (null == null)
and off goes the user.
You might want to try something like
if($username && $password);
[
//info is provided
]
else
[
echo "You did not provide the proper information needed for login.";