Hari KT

Hook before a 404 exception

Recommended Posts


Thank you for the wonderful CMF. This is my first question to the PW community as I started with it.

I am in the process of trying to create a module. The basic need is I want to change the content of the 404 page, if the route is something special.

Eg : say the request is for http://processwire.localhost/hello and if I know the path doesn't exists I want to do something special.

public function init()
    $this->addHookBefore('ProcessController::execute', $this, 'someMethod'); 
public function someMethod($event)
    // also how do I access the $_SERVER variables from processwire point of view

 Also how do I access the $_SERVER variables from a PW context. Something like $pages->get('SERVER').

  • Like 1

Share this post

Link to post
Share on other sites

Thank you. I found the correct hook, that solves the first part. Like

public function init()
    $this->addHookAfter('ProcessPageView::pageNotFound', $this, 'someMethod');

Now looking for the second part . About the $_SERVER usage.

Thank you.

Share this post

Link to post
Share on other sites

Welcome Hari!

Not sure if this is what you want, but you can access the server variables like in normal PHP. 

$request_method = $_SERVER['REQUEST_METHOD'];
echo $request_method;

Or to go through all of the server variables

$server_vars = $_SERVER;

foreach ($server_vars as $var) {
	echo $var; 

Otherwise maybe look at some of the options available via the "system configuration" method $config-> 


Share this post

Link to post
Share on other sites

Thank you @Michael.

No I wasn't looking how I can iterate through the server variables.  According to what I learned using global values inside the class seems not a good way, so was wondering whether the post values, what sort of REQUEST_METHOD is already called is available via some objects which is called in bootstrap.

You can have a test to the code below to see what I mean

// see how the o/p differs
$_SERVER = array();

That becomes a hell to all if someone set like this in a module.

Share this post

Link to post
Share on other sites

If I understand your needs correctly, I don't think you need hooks. The 404 page has a separate template, so you could move your logic there:

if ($uri == 'hello') {
  echo 'hello';
} else {
  echo 'not welcome';

Share this post

Link to post
Share on other sites

Thanks @Wanze .

So to make it clear, what I am doing is moving the index.php to a seprate folder.



So the problem we are going to face is none of the images, js, css cannot be accessed.

A good example is call for http://processwire.localhost/site/templates/styles/main.css will result in 404 , for the only entry point is index.php . I can create symbolic links, but I thought of making a module ;) . So my goal is to create a module which can check whether the request is for a certain type ( css, image, js ) and return the content according to the type. (I have already created the same.)

About the usage of $_SERVER seems a bad idea to me as I mentioned earlier. If some ( 3rd party module ) replaces the content, hard to deal.

For those who don't know me, I have a bit of background in aura project ( and some other open-source projects ) and you can see the how the $_SERVER is accessed. Once you set, even if someone resets the superglobals the object value never changes.

Let me show you an example from aura v2

use Aura\Web\WebFactory;

$web_factory = new WebFactory($GLOBALS);
$request = $web_factory->newRequest();
echo " Request uri is " . $request->server->get('REQUEST_URI');
$_SERVER['REQUEST_URI'] = 'oye I am changing';
echo $request_uri = $request->server->get('REQUEST_URI', '');

If you have tried the above example you will understand what I mean. ( I am not promoting aura here, my goal is to make PW things better and secure. I am also going to search for the thread composer and how it is utilized )

If anyone is interested have a look into the links below





Thank you.

Share this post

Link to post
Share on other sites

Hello I'm having trouble figuring out how to use the code above to run a hook before an error 404 exception, for when a template file is run with due to $config->prependTemplateFile before any template file runs.

//wire()->addHookBefore('Page::path', function($event) { @note: this or below, both work.
$pages->addHookBefore('ProcessPageView::pageNotFound', function($event) {
  echo "<h1>hello</h1>";
  $page = $event->object;
  if($page->template == 'LinkShortener') {// template used by 'post-a'
    $dapath = str_replace("/", "", $_SERVER[REQUEST_URI]);
      $redirectTo = $pages->find("template=LinkShortener,name=$dapath")->first();
      header("Location: $redirectTo->full_path");

The text hello does not display for an error 404.

What is going on?

Share this post

Link to post
Share on other sites


I don't think the above will work, because most of the time when a 404 occurs, that's because the $page could not be found. So there is no $page available. The only place where you could add such a hook would be in /site/init.php, because usually a 404 would have been thrown already by the time your prependTemplateFile gets called—meaning it won't get called, except for doing the rendering of the actual 404 page. 

Where you might be able to get it to work is for your own manually thrown 404s in your template files. i.e. throw Wire404Exception(); or for pages that exist, but the user didn't have access to view them due to access control settings. 

Your $page = $event->object; is not a Page object, but rather a ProcessPageView object. If there was a $page available when the 404 was triggered, it would be in $event->arguments(0); That can either be a Page object, a NullPage, or null. 

Your $dapath variable probably doesn't have what you need, and needs to be sanitized as well. Try using $input->url() instead. Note that it's going to have slashes in it, since it is a URL, which means it's not going to work for your selector where you've got "name=$dapath". You'll want to extract out the first name in the URL and use that, i.e. 

$parts = explode('/', trim($input->url(), '/'));
$name = array_shift($parts); 
$name = $sanitizer->pageName($name);
// now you can use $name in a selector

If you needed to, it should be fine to substitute the $input->url()  with $_SERVER['REQUEST_URI'] since it is being sanitized with $sanitizer->pageName(). Though I think the values will likely be identical, so I'd prefer the $input->url(). 

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By bernhard
      This module was built to fill the gap between simple $pages->find() operations and complex SQL queries.
      The problem with $pages->find() is that it loads all pages into memory and that can be a problem when querying multiple thousands of pages. Even $pages->findMany() loads all pages into memory and therefore is a lot slower than regular SQL.
      The problem with SQL on the other hand is, that the queries are quite complex to build. All fields are separate tables, some repeatable fields use multiple rows for their content that belong to only one single page, you always need to check for the page status (which is not necessary on regular find() operations and therefore nobody is used to that).
      In short: It is far too much work to efficiently and easily get an array of data based on PW pages and fields and I need that a lot for my RockGrid module to build all kinds of tabular data.

      Basic Usage

      Docs & Download
      180817, v1.0.6, support for joining multiple finders 180810, v1.0.5, basic support for options fields 180528, v1.0.4, add custom select statement option 180516, change sql query method, bump version to 1.0.0 180515, multilang bugfix 180513, beta release <180513, preview/discussion took place here: https://processwire.com/talk/topic/18983-rocksqlfinder-highly-efficient-and-flexible-sql-finder-module/
    • By OLSA
      Hello for all,
      ConfigurationForm fieldtype module is one my experiment from 2016.
      Main target to build this module was to store multiple setup and configuration values in just 1 field and avoid to use 1 db table to store just single "number of items on page", or another db table to store "layout type" etc. Thanks to JSON formatted storage this module can help you to reduce number of PW native fields in project, save DB space, and reduce number of queries at front-end.
      Install and setup:
      Download (at the bottom ), unzip and install like any other PW module (site/modules/...). Create some filed using this type of field (ConfigurationForm Fieldtype) Go to field setup Input tab and drag some subfields to container area (demo). Set "Name" and other params for subfields Save and place field to templates ("Action tab") How to use it:
      In my case, I use it to store setup and configurations values, but also for contact details, small content blocks... (eg. "widgets").
      Basic usage example:
      ConfigForm fieldtype "setup" has subfields:
      "limit", type select, option values: 5, 10, 15, 20
      "sort", type select, option values: "-date", "date",  "-sort", "sort"
      // get page children (items) $limit = isset($page->setup->limit) ? $page->setup->limit : 10; $sort = isset($page->setup->sort) ? $page->setup->sort : '-sort'; $items = $page->children("limit=$limit, sort=$sort");  

      Provide option to search inside subfields Provide multilanguage inputs for text and textarea field types Provide option for different field layout per-template basis Do not place/use field type "Button" or "File input" because it won't works. Please read README file for more details and examples Module use JSON format to store values. Text and textarea field types are multilanguage compatible, but please note that main target for this module was to store setup values and small content blocks and save DB space. Search part inside JSON is still a relatively new in MySQL (>=5.77) and that's on you how and for what to use this module.
      Initial point for this fieldtype was jQuery plugin FormBuiled and thanks to Kevin Chappel for this plugin.
      In field type "link" I use javascript part from @marcostoll module and thanks to him for that part.
      Edit: 14. August 2018. please delete/uninstall previously downloaded zip
    • By bernhard
      @Sergio asked about the pdf creation process in the showcase thread about my 360° feedback/survey tool and so I went ahead and set my little pdf helper module to public.
      Description from PW Weekly:
      Modules Directory: https://modules.processwire.com/modules/rock-pdf/
      Download & Docs: https://gitlab.com/baumrock/RockPdf
      You can combine it easily with RockReplacer: 
      See also a little showcase of the RockPdf module in this thread:
    • By Thomas Diroll
      Hi guys I'm relatively new to PW and just finished developing a page for a client. I was able to include all necessary functionality using the core fieldtypes but now I it seems that I need to extend them with a custom one. What I need is a simple button, that copies the absolute url (frontend not PW-backend) of the page which is currently edited to the clipboard. As this feature is only needed inside a specific template, I tend to use a custom fieldtype which provides this feature. I've been looking inside the core modules code (eg. FieldtypeCheckbox.module) but I don't really get the structure of it and how its rendered to the admin page. I also didn't find a lot of tutorials covering custom fieldtypes.
      Maybe some of you could give me some tips on how to write a basic custom fieldtype that renders a button which copies the value of
      page->httpUrl() to the clipboard using JS. Thanks!
    • By bernhard
      Some of you might have followed the development of this module here: https://processwire.com/talk/topic/15524-previewdiscussion-rockdatatables/ . It is the successor of "RockDataTables" and requires RockFinder to get the data for the grid easily and efficiently. It uses the open source part of agGrid for grid rendering.
      ProcessWire is awesome for creating all kinds of custom backend applications, but where it is not so awesome in my opinion is when it comes to listing this data. Of course we have the built in page lister and we have ListerPro, but none of that solutions is capable of properly displaying large amounts of data, for example lists of revenues, aggregations, quick and easy sorts by the user, instant filter and those kind of features. RockGrid to the rescue 😉 
      100k+ rows Instant (client side) filter, search, sort (different sort based on data type, eg "lower/greater than" for numbers, "contains" for strings) extendable via plugins (available plugins at the moment: fullscreen, csv export, reload, batch-processing of data, column sum/statistics, row selection) all the agGrid features (cell renderers, cell styling, pagination, column grouping etc) vanilla javascript, backend and frontend support (though not all plugins are working on the frontend yet and I don't plan to support it as long as I don't need it myself)  
      While there is an option to retrieve data via AJAX the actual processing of the grid (displaying, filtering, sorting) is done on the client side, meaning that you can get into troubles when handling really large datasets of several thousands of rows. agGrid should be one of the most performant grid options in the world (see the official example page with a 100k row example) and does a lot to prevent problems (such as virtual row rendering), but you should always have this limitation in mind as this is a major difference to the available lister options that do not have this limitation.
      Currently it only supports AdminThemeUikit and I don't plan to support any other admin theme.
      Download: https://gitlab.com/baumrock/RockGrid
      Installation: https://gitlab.com/baumrock/RockGrid/wikis/Installation
      Quikckstart: https://gitlab.com/baumrock/RockGrid/wikis/quickstart
      Further instructions: https://gitlab.com/baumrock/RockGrid/wikis/quickstart#further-instructions
      Module status: alpha, License: MIT
      Note that every installation and uninstallation sends an anonymous google analytics event to my google analytics account. If you don't want that feel free to remove the appropriate lines of code before installation/uninstallation.
      You can contribute to the development of this and other modules or just say thank you by
      testing, reporting issues and making PRs at gitlab liking this post buying me a drink: paypal.me/baumrock/5 liking my facebook page: facebook.com/baumrock hiring me for pw work: baumrock.com  
      Support: Please note that this module might not be as easy and plug&play as many other modules. It needs a good understanding of agGrid (and JavaScript in general) and it likely needs some looks into the code to get all the options. Please understand that I can not provide free support for every request here in the forum. I try to answer all questions that might also help others or that might improve the module but for individual requests I offer paid support for 60€ per hour.
      180730 support subdir installations 180711 bugfix (naming issue) 180630 alpha realease  
      Use Cases / Examples:
      Colored grid cells, Icons, Links etc. The Grid also has a "batcher" feature built in that helps communicating with the server via AJAX and managing resource intensive tasks in batches:

      Filters, PW panel links and instant reload on panel close:

      You can combine the grid with a chart library like I did with the (outdated) RockDataTables module: