CakePHP redirect with status code 404
Asked Answered
F

3

9

For CakePHP errors I know that there exists CakeError and AppError solutions. But I need to make a redirection within controller.

In AppController there exists:

function afterFilter() {
    if ($this->response->statusCode() == '404')
    {
        $this->redirect(array(
            'controller' => 'mycontroller',
            'action' => 'error', 404),404
        );
    }
}

But this doesn't create a 404 status code. It creates a 302 code. I changed code to this:

$this->redirect('/mycontroller/error/404', 404);

But the result is same.

I added this, it didn't work also deprecated:

$this->header('http/1.0 404 not found');

How can I send a 404 code within controller redirect ?

Fork answered 29/6, 2012 at 20:57 Comment(0)
C
22

If you want to return a 404 error, use the built in CakeError support for it:

throw new NotFoundException();

You can throw this exception from your controller and it should generate a 404 response.

There are more built-in exceptions here.

If you are interested in making a custom error page, then see this post.

Otherwise, I don't think it is possible to return a 404 header code and still redirect. Http specifies redirect status codes to be in the 300s, and this is the convention CakePHP follows.

Corpulence answered 29/6, 2012 at 21:13 Comment(0)
N
7

For some reason using redirect() will change the status code to 3xx. If you want to execute another action and still return 404, you can do as follows:

$this->controller->response->statusCode(404);
$this->controller->render('/mycontroller/error/404');
$this->controller->response->send();

This will execute Mycontroller::error(404) without redirect.

Noncombatant answered 2/1, 2013 at 19:42 Comment(0)
M
1

CakePHP 3

use Cake\Network\Exception\NotFoundException;
...
throw new NotFoundException(__('Article not found'));
Marrissa answered 2/4, 2017 at 13:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.