Login script?

I’m trying to create a login function using
image
But, when I submit, I get a few errors
image
why are the session variables not set?
on

<?php
include '../db/pdo_conn.php'; 

echo '<pre>';print_r($_POST);echo '</pre>';

require 'config.php';


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

  echo '<pre>';print_r($data);echo '</pre>';


	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";
	}
	
  echo '<pre>';print_r($errors);echo '</pre>';

	if (empty($errors)) { // Input is correct, see if user exists
	  $sql = "SELECT * FROM users WHERE email=?";
	  $stmt = $pdo->prepare($sql);
	  $stmt->execute([$data['email']]);
				
	  echo $sql;
				
		if($result = $stmt->fetch())
		{
			if(!password_verify($data['password'], $result['password']))
			{
			  $errors['wrong'] = 'Incorrect email/password';
			}
			else
			{
			  $_SESSION['name'] = $result['first_name']. ' ' . $result['last_name'];
			  $_SESSION['email'] = $result['email'];
			  $_SESSION['role'] = $result['role'];
			  $_SESSION['success_message'] = 'You have logged in.';
						
			  echo '<pre>';print_r($_SESSION);echo '</pre>';
			}
		}
	}
}
?>

My database has

It would seem you’re not calling session_start(), which is required for sessions to work.

1 Like

The stored password values are not hashed, so password_verify() will never match anything. You also changed the logic so that it no longer does anything if the email wasn’t matched. You also missed the point about only storing the user id in a session variable, then querying on each page request to get any other user data.

1 Like

Based on the output, mab is correct. You’ve ended up in the password-didnt-match logic, but your only action in that section is to add an entry to the Errors array that… doesnt get output again, so you never see it.

rpkamp’s also correct that we don’t see a call to session_start, but we also dont see an opening PHP tag, so that may just be copy/pasting problems.

That was a post formatting issue which I have now fixed so the opening tag shows.

2 Likes

got it, thanks

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