I am using cakephp version 4. When I try to load my project, I get the error: This page isn’t working. localhost redirected you too many times ERR_TOO_MANY_REDIRECTS. So I googled the problem and found some debugging code. The site I found said to put the following in AppController:
public function redirect($url) {
debug($url);
debug(stackTrace());
die; }
When I paste in the code and refresh my browser, I get the error:
Fatal error: Declaration of App\Controller\AppController::redirect($url) must be compatible with Cake\Controller\Controller::redirect($url, int $status = 302): ?Cake\Http\Response in C:\xampp\htdocs\momp\src\Controller\AppController.php on line 31
line 31 is: class AppController extends Controller
The : ?Cake\Http\Response is part of the function declaration; it’s specifying that the return type of the function will be a Response object (or possibly null, indicated by the “?”).
But the “too many redirects” is usually a result of the login page not being excluded from authentication, so it redirects to the login page, which redirects to the login page, etc.
This is what I have in my UsersController. I baked it so it should be correct.
public function login()
{
$this->request->allowMethod(['get', 'post']);
$result = $this->Authentication->getResult();
//var_dump($result);
// regardless of POST or GET, redirect if user is logged in
if ($result->isValid()) {
// redirect to /mealplans after login success
$redirect = $this->request->getQuery('redirect', [
'controller' => 'Mealplans',
'action' => 'index',
]);
return $this->redirect($redirect);
}
// display error if user submitted and authentication failed
if ($this->request->is('post') && !$result->isValid()) {
$this->Flash->error(__('Invalid email or password'));
}
}
you need to add the following your userscontroller:
public function beforeFilter(\Cake\Event\EventInterface $event)
{
parent::beforeFilter($event);
// Configure the login action to not require authentication, preventing
// the infinite redirect loop issue
$this->Authentication->addUnauthenticatedActions([‘login’]);
}
Thanks, dirk. I had that in my UsersController already. I tried baking UsersController again but it didn’t create a login or logout method. I wonder why that is.
baking does not generate the login, logout or register action. You should have noticed that, when you first baked the userscontroller.
only you know which steps you followed to get the login action in your controller, so you have to check against the tutorial what is done and what is missing. CMS Tutorial - Authentication - 4.x
i think there is no need for this database field.
here is a short description of how password hashing works in cakephp 3 and cakephp 4 and a solution to your problem.
When I comment out the lines of code in my login method in UsersController, the page loads with no problem so something is wrong with my login method. I got the code for the method from the cakephp 4 tutorial.