How do you specify an HTTP status code in Cakephp?

2020-02-24 12:49发布

In my controller, I check a condition to see if the user is allowed to do something. If the check fails, I want to send a 403 back to the browser. How do I do that in Cakephp?

标签: cakephp
9条回答
来,给爷笑一个
2楼-- · 2020-02-24 13:36

Upon revisiting this question, and reading Adriano's comment on my previous answer (regarding redirecting the user to a friendly page), I have come up with a new solution.

Within a controller you can call $this->cakeError('error404') to generate a friendly 404 page. This can can be customised (as with other errors) by creating file at 'app/views/errors/error404.ctp'.

After having a closer look at the code for cakeError, my recommendation is to try extending Cake's ErrorHandler by creating a file at 'app/error.php' or (possibly more preferable) 'app/app_error.php'.

The code for your error403 (mimicking the error404 code) could read as follows:

class AppError extends ErrorHandler {
    function error403($params) {
        extract($params, EXTR_OVERWRITE);
        $this->error(array(
            'code' => '403',
            'name' => 'Forbidden',
            'message' => sprintf(__("Access was forbidden to the requested address %s on this server.", true), $url, $message)));
            $this->_stop();
     }
}

You should also be able to provide a custom view for this error by creating 'app/views/errors/error403.ctp'. Here is a modified version of the error404 view:

<h2><?php echo $name; ?></h2>
<p class="error">
    <strong>Error: </strong>
    <?php echo sprintf(__("Access was forbidden to the requested address %s on this server.", true), "<strong>'{$message}'</strong>")?>
</p>
查看更多
时光不老,我们不散
3楼-- · 2020-02-24 13:38

EDIT - This question is quite old and covers different versions of the CakePHP framework. Following is a summary of which version each answer applies to. Don't forget to vote on the solution that helps most.

EDIT #2 - A more detailed answer for CakePHP 2.x has been added by Mark37.

EDIT #3 - Added solution for CakePHP. (May 2018: CakePHP 3.5 did some function renaming, solution by Roberto is still valid.)


By looking at the relevant API code from the previous comment, it seems you can call Controller::header($status) to output a header without redirection. In your case, the proper usage is most likely:

$this->header('HTTP/1.1 403 Forbidden');
查看更多
Lonely孤独者°
4楼-- · 2020-02-24 13:40

Notes concerning CakePHP 3.x seem to be missing, so to make this thread complete:

For CakePHP 3.x use:

$response = $this->response->withStatus(403);
return $response;

For versions before CakePHP 3.3.x you can use the same style as CakePHP 2.x:

$this->response->statusCode('code');

Note that using the PHP function directly also works (http_response_code(403); die();), though using the response object seems like the intended method.

查看更多
登录 后发表回答