3 forms submitted to 1 page

ok, moving on to logging in…I have

$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;

the result


the password is wrong and why did the session variable not change?

^ I guess someone has already pointed out how storing plain-text passwords is A Bad Thing?

And, how is this working?

<input type="email" class="form-control" id="Email" name="Email" required>

in your form, but

if ($data['email'] === '')

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.

Because your logic is bad.

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 -

  1. Build and execute a SELECT query to try to match the entered email address.
  2. Fetch a single row of data and test if there was fetched data.
  3. 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.
  4. If the email was found, use password_verify() to test if the submitted password matches the previously hashed value.
  5. If the password doesn’t verify, setup the same common “Incorrect email/password” message for the user.
  6. 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.
  7. Because this section of code can produce its own user/validation errors, end this branch of conditional logic }
  8. 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.

like…

    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";
	}
	$sql = "SELECT * FROM users WHERE email=?";
	$stmt = $pdo->prepare($sql);
	$stmt->execute([
		$data['email'}
	]);	
	if($result = $stmt->fetch()) 
	{
		if(!password_verify($data['password'], $result['password'])) 
		{
			$errors['wrong'] = 'Incorrect email/password';
		}			
		
	} else {
		$errors['wrong'] = 'Incorrect email/password';
	}
	if(empty($errors))

		$_SESSION['name'] = $row['first_name'].' '$row['last_name'];
		$_SESSION['email'] = $row['email'];
		$_SESSION['success_message'] = 'You entered the correct email/password.';

	}
	break;

then in my navbar

<nav class="navbar navbar-expand-lg">
  <div class="container-fluid">
    <a class="navbar-brand" href="index.php">Boy Scout Tracker</a>
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarText" aria-controls="navbarText" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarText">
      <ul class="navbar-nav me-auto mb-2 mb-lg-0">
        <li class="nav-item">
          <a class="nav-link active" aria-current="page" href="index.php">Home</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="about.php">About us</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="requirements.php">Requirements</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="contact.php">Contact us</a>
        </li>
      </ul>
      <span class="navbar-text">
<?php
if(isset($_SESSION['emall'])) {
	echo 'You&nbsp;are&nbsp;logged&nbsp;in&nbsp;as&nbsp;&nbsp;'.$_SESSION['name']['name'].'&nbsp;&nbsp;';
	echo '<a class="btn btn-danger btn-sm" href="logout.php" role="button">Logout</a>';
} else {
	echo '<a class="btn btn-outline-light btn-sm" href="#register" role="button">Register</a>';
	echo '<a class="btn btn-outline-light btn-sm" href="#login" role="button">Login</a>';
}
?>	      
	  </span>
    </div>
  </div>
</nav>  

Typo alert.

Well, there is no point in querying the database if the email is missing or invalid or if the password is empty, is there?

<?php

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";
    }
    if (empty($errors)) { // Input is correct, see if user exists
        $sql = "SELECT * FROM users WHERE email=?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([
            $data['email'],
        ]);
        if($result = $stmt->fetch())
        {
            if(!password_verify($data['password'], $result['password']))
            {
                $errors['wrong'] = 'Incorrect email/password';
            }
            else // known user/pass, log in
            {
                $_SESSION['name'] = $result['first_name']. ' ' . $result['last_name'];
                $_SESSION['email'] = $result['email'];
                $_SESSION['success_message'] = 'You entered the correct email/password.';
            }
        } else {
            $errors['wrong'] = 'Incorrect email/password';
        }
    }
    break;

ok, the form works now, for logging out,

<a href="?logout'>Logout</a>

then

if(isset($_GET['logout'])) {
    session_destroy();
}

ok?

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.

thanks

when I login, the url changes to
image
but when I logout, the url is still
image
shouldn’t the email and success_message session variables change?

    case 'logout':

	unset($_SESSION['email']);
    $_SESSION['success_message'] = 'You logged out.';
	//die(header("Refresh:0"));	

   	break;

when i press the login button changs to add #login


when I enter the correct email/password, I get a sucess message buT the URL
remains like
image
Dont I need to cut off tthe login part?
my logic

    if (empty($errors)) { // Input is correct, see if user exists
        $sql = "SELECT * FROM users WHERE email=?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([
            $data['email'],
        ]);
        if($result = $stmt->fetch())
        {
            if(!password_verify($data['password'], $result['password']))
            {
                $errors['wrong'] = 'Incorrect email/password';
            }
            else // known user/pass, log in
            {
                $_SESSION['name'] = $result['first_name']. ' ' . $result['last_name'];
                $_SESSION['email'] = $result['email'];
                $_SESSION['success_message'] = 'You entered the correct email/password.';
				//die(header("Refresh:0"));	
          }
        } else {
            $errors['wrong'] = 'Incorrect email/password';
        }
    }

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.