简体   繁体   中英

How do i add the password_hash function on a simple login system?

I am using PHP and MySQL to create a login system. The page only requires the user to login and their is no option for them to register.

I have the passwords stored in my database already as plain text and i am aware this is not safe at all.

What steps would i take to make this more secure and hash the password that is already stored in the database?

Would i need to go back and alter my database?

Here is some code i am using at the moment:

if($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (empty($_POST['username']) || empty($_POST['password'])) {
        $error = "Enter Username and Password";
    } else {    
        $username = $_POST['username'];
        $password = $_POST['password'];

        include('dbconx.php');

        $sql = "SELECT * from admin where password='$password' AND     username='$username'";
        $result = mysqli_query($con,$sql) or die(mysqli_error());
        $count = mysqli_num_rows($result);

        if ($count == 1) {
            $_SESSION['login_user'] = $username; // Initializing Session
            header("location: confirm.php"); // Redirecting To Other Page
        } else {
            $error = "Username or Password is incorrect";
        }
        mysqli_close($con); // Closing Connection
    }
}

The important points were already written in the comments. To sum it up:

  • password_hash and password_verify are the functions to use in PHP
  • You'd have to write a script which goes through all your already stored passwords (in plaintext) and hash them with password_hash and resave them to the database.
  • You should read about SQL-injections. Use (at least) mysqli_escape_string. Much, much better ist to use prepared statments. ( http://php.net/manual/en/pdo.prepared-statements.php )
  • I don't know your database-structure, but normally you don't need to alter anything there, but you will have to check your password field is large enough to hold the hash VARCHAR(255) is recommended as password_verify() may get changed in future versions of PHP and this should be big enough to hold any future hashing output.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM