$data = []; // array to hold a trimmed working copy of the form data. will also receive the initial data when editing/updating existing data
$errors = []; // array to hold user/validation errors
// post method form processing
if($_SERVER['REQUEST_METHOD'] == "POST")
{
$data = array_map('trim',$_POST);
switch($data['type'])
{
case 'login':
if($data['email'] === '')
{
$errors['email'] = "Email is required";
}
else if(!filter_var($data['email'],FILTER_VALIDATE_EMAIL))
{
$errors['email'] = "Email must be in correct format.";
}
if($data['password'] === '')
{
$errors['password'] = "Password is required";
}
// in no errors, use the submitted data
if(empty($errors))
{
$sql = "SELECT * FROM users WHERE email=? AND password=? ";
$stmt = $pdo->prepare($sql);
$stmt->execute([
$data['email'],
$data['password']
]);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($result as $row) {
$password = $row['password'];
if(!password_verify($data['password'], $password))
{
$errors['match'] = "User not found";
}
$_SESSION['user'] = $row;
$_SESSION['success_message'] = 'You entered the correct email/password.';
}
}
break;
in your code. Why is it not complaining about the difference in element names? They’re not being changed by array_map, but suddenly they’ve changed from being capitalised to all lower case.
You are using password_hash() in the registration code to save a hash of the entered password. You must use password_verify() in the login code.
The login logic should -
Build and execute a SELECT query to try to match the entered email address.
Fetch a single row of data and test if there was fetched data.
If there is not a fetched row of data, the email address wasn’t found. Setup a common “Incorrect email/password” message for the user. You don’t want to confirm the existence of email address for hackers/bots.
If the email was found, use password_verify() to test if the submitted password matches the previously hashed value.
If the password doesn’t verify, setup the same common “Incorrect email/password” message for the user.
If the password does verify, store the user id (autoincrement primary index) in an appropriately named session variable, such as $_SESSION[‘user_id’]. You should query on each page request to get any other user data, such as the username, permissions, … so that any changes made to this other user data will take effect on the very next page request.
Because this section of code can produce its own user/validation errors, end this branch of conditional logic }
Put the final - // if no errors, success logic, where you setup the success message and perform the redirect to exact same URL of the current page.
Finally, if there is currently a logged in user, you should not display the login form or run the login form processing code.
You should use a post method form for the logout action. A session can hold data for other things beside the login. You should only unset() the specific session variable(s) that where set in the login code.