I am trying to learn PHP and I am steadely on my way by following a course about PHP.
For exercise I have to build an app that requires login and sessions.
In my UserController I use the code below to login:
<?php
class UserController extends Controller {
public function login() {
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$username = $_POST['username'];
$password = $_POST['password'];
$userModel = $this->model('User');
$user = $userModel->authenticate($username, $password);
if ($user) {
$_SESSION['user'] = $user;
//Redirect.
header('Location: /home/index');
exit();
} else {
$error = "Invalid username or password";
$this->view('users/login',['heading' => 'User Login']);
}
} else {
$this->view('users/login',['heading' => 'User Login']);
}
}
?>
My User Model looks like this:
<?php
class User extends Database {
//Check authentication of the user.
public function authenticate($username, $password) {
$stmt = $this->db->prepare("SELECT * FROM users WHERE username = :username");
//// Retrieve all results from the query as an associative array (PDO::FETCH_ASSOC). Each record is returned as an array with column names as keys.
$stmt->bindParam(':username', $username);
$stmt->execute();
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if ($user && password_verify($password, $user['password'])) {
return $user;
}
return false;
}
?>
The problem is that the $_SESSION[‘user’][‘username’] gets the value NULL.
I hop you can help me resolve this issue.