I'm doing a login page, I'm a beginner in PHP so you may see that my code doesn't look the most effective, but in time I will improve my skills. I've got a problem in the following code, when I'm trying to log in if I leave the password blank, the user may enter without password, but if I'm typing something, even 1 character, the code works. Why does my code not work correctly with a blank password, and how may I fix it?
Here's the code:
<?php
if($_POST["email"] == null || $_POST["password"] == null )
header("Location:index.php");
$email = $_POST["email"];
$password = $_POST["password"];
/*The Function checks if there's any user if that email - Primiary Key!*/
function UserExist()
{
global $email,$password;
$con = mysqli_connect("127.0.0.1:3306", "root", "root", "photoshare");
if(mysqli_connect_errno($con))
{
echo "לא הצליח להתחבר למסד נתונים</br>". mysqli_connect_error();
}
else
{
/*result == Checks if the user exits*/
$result = mysqli_query($con, "SELECT * FROM tbl_users WHERE email='$email'") or die(mysqli_error($con)); //Query which checks if the email exits in the db
if(!mysqli_num_rows($result))
header("Location:index.php");
PasswordExist($password); // checks if both of passwords are equals
}
mysqli_close($con);
}
//Checks if both password are equals
function PasswordExist($password)
{
global $email,$password;
$con = mysqli_connect("127.0.0.1:3306", "root", "root", "photoshare"); // Connect db
$query = "SELECT password FROM tbl_users WHERE email='$email'";//Spefic Row and Column !
$result = mysqli_query($con, $query);
$realPassword; // The real password from the db
//The while loop is taking the row which the the destination is does,and take by is column too . it means it's take his x and y.
while($realPassword = mysqli_fetch_array($result))
{
echo $realPassword[0]; //The Password from db
if($realPassword[0] != $password)
{
echo 'הסיסמא שגוייה אנא נסו להתחבר שנית<a href="index.php">חזרה לדף הבית</a>'; //Error massage if the passwords are difrrent
}
}
mysqli_close($con);
}
//Gets username nickname
function UserNameDetails()
{
global $email,$password;
$con = mysqli_connect("127.0.0.1:3306", "root", "root", "photoshare");
$query = "SELECT nickname FROM tbl_users WHERE email='$email'";//Spefic Row and Column !
$result = mysqli_query($con, $query);
$nickname;
while($nickname = mysqli_fetch_array($result))
{
echo $nickname[0];
setcookie("loggerUserNickName", $nickname[0], time()+1800); //Create cookie which save nickname of the user
}
mysqli_close($con);
}
//Change login.php form - as reason the user is logged.
function fileLoginPhpChanger()
{
$file = "login.php";
$fh = fopen($file, 'w');
$data =
'
<?php
if($_COOKIE["loggerUserNickName"]==null)
header("Location:loggedoutSpeical.php");
?>
<div id="logged">
שלום, <?php echo $_COOKIE["loggerUserNickName"];?>
</br>
<a href="loggedout.php">לניתוק מן המשתמש</a>
</div>
';
fwrite($fh, $data);
fclose($fh);
}
UserExist();
UserNameDetails();
fileLoginPhpChanger();
?>