Vairis Vairis - 1 month ago 6
PHP Question

PHP - Why is session still being created?

Good day, while doing my project, I did stuck on Login page.

This might be really trivial question or maybe even duplicate, but I can't find any solution online.

For some reason, my php script simply skips my login form and keeps making session and redirecting to index.php.

Here is my php script, for checking if email and password exist in databse:


if(isset($_POST['login'])) {
require 'connect.php';

$email = $_POST['email'];
$password = $_POST['password'];
$select_userdata = "select * from users where password ='$password' AND email = '$email'";

$run_check = mysqli_query($dbconfig, $select_userdata);
$check_user = mysqli_num_rows($run_check);

/**Error part**/
if ($check_user == 0) {
echo "<script>alert('Password or email is incorrect')</script>";
echo "<script>window.open('login.php','_self')</script>";
} else {
$_SESSION['email'] = $email;
echo "<script>alert ('You Have Been Logged in')</script>";
header('Location: index.php');
exit;
}
}
if(isset($_GET['logout'])) {
unset($_SESSION['email']);
}


For some reason, script does not care, if I have email and password in database or not. It "pretends" that there is such email address and password, and skips to $_SESSION['email'] = $email;

My question is, what am I doing wrong, and how do I fix it?

Answer

Problem is in your logic not your code. $check_user is 0 or more there is no difference for your code. it always reach the $_SESSION['email'] = $email; line. Try this:

<?php
session_start();
include'functions/dbconfig.php';

if(isset($_POST['login'])) {
    require 'functions/connect.php';
    $email = $_POST['email'];
    $password = md5($_POST['password']);
    $select_userdata = "select * from users where password ='$password' AND email = '$email'";


    $run_check = mysqli_query($dbconfig, $select_userdata);
    $check_user = mysqli_num_rows($run_check);

    if ($check_user == 0)
    {
        echo "<script>alert('Password or email is incorrect')</script>";
        echo "<script>window.open('login.php','_self')</script>";
    }
    else
    {
        $_SESSION['email'] = $email;
        echo "<script>alert ('You Have Been Logged in')</script>";
        header('Location: index.php');
        exit;
    }
}
if(isset($_GET['logout'])) {
    unset($_SESSION['email']);
}
?>
Comments