Chris J Allen
Chris J Allen

Reputation: 19207

Can I make CakePHP return a suitable status code based on certain conditions?

This question is slightly related to my old post Dealing with Alias URLs in CakePHP

After much thought, I am exploring the option of having a custom 404 script in my Cake App, that is reached when a URL does not map to any controllers/actions. This script would check $this->here and look it up in a database of redirects. If a match is found it would track a specific 'promo' code and redirect.

I'm thinking status codes. Can I make my script return a suitable status code based on certain conditions? For example:

  1. URL matches a redirect - return a 301
  2. URL really does not have a destination - return a 404.

Can I do this?

EDIT:

What about this? Anyone see any problems with it? I put it in app_controller.

function appError($method, $params) {

    //do clever stuff here

}

Upvotes: 1

Views: 3569

Answers (3)

mattalxndr
mattalxndr

Reputation: 9408

I'd like to augment felixge's answer.

This version outputs a 404 error to the browser:

class AppError extends ErrorHandler
{
        function _outputMessage($template)
        {
                if ($template === 'error404') {
                        $Dispatcher = new Dispatcher();
                        $Dispatcher->dispatch('legacy_urls/map', array('broken-url' => '/'.$params['url']));
                        return;
                }
                parent::_outputMessage($template);
        }
}

Upvotes: 0

adam
adam

Reputation: 4005

I've always created app\views\errors\missing_action.ctp and app\views\errors\missing_controller.ctp

Cake will automatically display one of those views when a url does not map out to a controller or its methods.

Unless there is a certain need for the error codes that you did not give, this would work perfectly!

Upvotes: 4

Felix Geisendörfer
Felix Geisendörfer

Reputation: 3042

This should work. Assuming you redirect 404's at a LegacyUrls::map() controller action. The code needs to be stored in app/app_error.php:

<?php
class AppError extends ErrorHandler{
    function error404($params) {
        $Dispatcher = new Dispatcher();
        $Dispatcher->dispatch('/legacy_urls/map', array('broken-url' => '/'.$params['url']));
        exit;
    }

    function missingController($params) {
        $Dispatcher = new Dispatcher();
        $Dispatcher->dispatch('/legacy_urls/map', array('broken-url' => '/'.$params['url']));
        exit;
    }
}
?>

Good luck!

Upvotes: 6

Related Questions