Kohana 3 :: alternate 404 method

controller

<?php defined('SYSPATH') or die('No direct script access.');

if ( ! $this->_auth->logged_in('login'))
{
 throw new Kohana_Exception('You are not allowed to view this resource.');
}

bootstrap.php

<?php defined('SYSPATH') or die('No direct script access.');

try
{
 echo Request::instance()
  ->execute()
  ->send_headers()
  ->response;
}
catch (Kohana_Exception $e)
{
 echo Request::factory('static/404')->execute()->send_headers()->response;
}

404 action

<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Static extends Controller_Template_Twig
{
 /**
  * 404 page
  */
 public function action_404()
 {
  // Here we check to see if a 404 came from our website. This allows the
  // webmaster to find broken links and update them in a shorter amount of time.
  if (isset ($_SERVER['HTTP_REFERER']) AND strstr($_SERVER['HTTP_REFERER'], $_SERVER['SERVER_NAME']) !== FALSE)
  {
   // Set a local flag so we can display different messages in our template.
   $this->template->local = TRUE;
  }

  // Requested page.
  $this->template->page = url::site(Request::instance()->uri);

  // HTTP Status code.
  $this->request->status = 404;
 }
}

1 comments:

DrPheltright said...

If you don't feel happy about wrapping your request instance in a try... catch statement you can write your own exception handler, like I have with my Prophet module (https://github.com/DrPheltRight/Prophet) and Errorist by Mathew Davies (https://github.com/ThePixelDeveloper/kohana-bits-and-bobs/tree/master/modules/errorist).

The method described in this blog post handles all errors (not just page not found) as 404 errors!!

Post a Comment