Search code examples
phpcakephphttp-response-codes

How to send a 410 gone in cakephp 2.x


I want to the server a 410 gone response for my old unpublished URLs in CakePHP.

CakePHP provides a variety of exceptions like 404, 500 etc. but there is nothing like 410 gone.

Is there any way I can server 410 gone response if someone opens an old URL that no longer exists on the website but used to be.

Thanks,


Solution

  • I did followings to resolved this.

    I added "gone" function in "AppExceptionRenderer"

    public function gone($error) {
    
            $this->controller->layout = 'nopageexists';
    
            $this->controller->set('title_for_layout', __('example.com: Page not found'));
            $this->controller->set('meta_description', '' );
            $this->controller->set('meta_keywords', '');
    
            // This will execute 404 Error Page without redirection added by vinod...
            $this->controller->response->statusCode(410);
            $this->controller->render('/Errors/error404');
            $this->controller->response->send();
        }
    

    Created a custom class in app/Lib/myException.php

    class GoneException extends CakeException {
    
    /**
     * Constructor
     *
     * @param string $message If no message is given 'Not Found' will be the message
     * @param integer $code Status code, defaults to 410
      */
        /*
        public function __construct($message = null, $code = 410) {
            if (empty($message)) {
                $message = 'Gone';
            }
            parent::__construct($message, $code);
        }
        */
        protected $_messageTemplate = 'Test';
    }
    

    Added below in Controller where I want to show 410 gone.

    throw new GoneException('Gone', 410);
    

    This worked for me.