-2

I am trying to write a login script. But cant write it and facing some problems.

<?php
    include 'Database.php';

    if (isset($_POST['sub'])) {
        if (!empty($_POST['email']) && !empty($_POST['password'])) {
            $db = new User();
            $query = $db->query('SELECT * FROM users WHERE email="'.$_POST['email'].'" AND pasword="'.$_POST['password'].'"');

            if ($query && $query->num_rows > 0) {
                $row = $query->fetch_assoc();

                if (password_verify($_POST['password'], $row['password'])) {
                    echo "Log in Success";
                }
                else {
                    echo "Password doesnt match!";
                }
            }
            else {
                echo "Not found";
            }
        }
        else {
            echo "Fill the blanks";
        }
    }
    else {
        echo "Error";
    }
?>

How can I set session here.
And I know I that have some errors here please someone hep me to fix these.

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
SakibOvi
  • 1
  • 1
  • Before you do *anything*, fix the SQL injection bug in your code! See [How can I prevent SQL injection in PHP?](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php). – grooveplex Oct 17 '19 at 15:40
  • 2
    **Never store plain text passwords!** Please use ***PHP's [built-in functions](http://jayblanchard.net/proper_password_hashing_with_PHP.html)*** to handle password security. If you're using a PHP version less than 5.5 you can use the `password_hash()` [compatibility pack](https://github.com/ircmaxell/password_compat). ***It is not necessary to [escape passwords](http://stackoverflow.com/q/36628418/1011527)*** or use any other cleansing mechanism on them before hashing. Doing so *changes* the password and causes unnecessary additional coding. – Jay Blanchard Oct 17 '19 at 15:48

1 Answers1

0

First of all, I recommend using prepared statements for your query building. This makes sure that SQL injection is not possible.

Secondly, you can assign session variables once you call session_start()

<?php
session_start(); //Call at the top of your page.
//Do login stuff
if(login_success) {
    $_SESSION['userId'] = $user->Id; //Taken from the select.
}
?>
ThePerplexedOne
  • 2,920
  • 15
  • 30