Keeping unencrypted passwords in the database is strongly discouraged. This can lead to data loss and hacking of user accounts and more.
It is recommended to keep password hashes in the database.
Let’s hashing our password before sending it to the database:
password_hash("password", PASSWORD_DEFAULT);
password – your password
PASSWORD_DEFAULT – the bcrypt algorithm is used
After hashing, our password will look like this:
$password = '$2y$10$alggKPflvFSw3xtSsIIn2eqjxdDplJoaUqc7kxzDDQK/OGMWtUhdy';
Let’s check whether our password corresponds to its hash password_verify:
$password = '$2y$10$alggKPflvFSw3xtSsIIn2eqjxdDplJoaUqc7kxzDDQK/OGMWtUhdy'; password_verify('password', $password);//return true or false
Now let’s use this as an example. We will enter the secret.php page only after entering the login and password. To do this, imagine that we have an HTML form in which you need to enter the password and login. The form sends data by the POST method where our PHP script processes it.
PHP authorization will look like this:
if (!empty($_POST)) {//check that the POST request is not empty //check if the login has arrived and verify our password by comparing the password with its hash if ($_POST['login'] == $login && password_verify($_POST['password'], $password)) { //if we record the session well and send the user to the page secret.php $_SESSION['auth'] = 1; $_SESSION['res'] = 'Success'; header("Location: secret.php"); die; } else { $_SESSION['res'] = 'Error'; header("Location: index.php"); exit; } }