404 page does search in Drupal
Boris Mann created a 404 pagehack, which contained a block of code which is perfect for making a custom 404 page that automatically searches for the terms used in the URL. This is a solution to giving users other options of pages if you remove a file or node and a search engine keeps sending users to the old URL. I made some tweaks to the code.
To use this on your Drupal 4.6-based site:
1. Create a node of type "page"
2. Set the type to "PHP"
3. Paste in the code below
4. Set the title to what you want people to see when they try and access a page that doesn't exist, e.g. "Sorry! We couldn't find the page you were looking for"
5. Enter something like "404" or "custom404" as the path alias (path.module required).
6. In the main admin -> settings page, enter in the path alias name from the previous step into the "Default 404 (not found) page" field
Now, when people try to access pages which don't exist (e.g. /notarealnode), an automatic search will be performed, as well as a search form presented.
This code does have a problem in that the search results will still display the paginator at the bottom. If you click to go to the next page of automatic search results, the pagehack doesn't know how to handle it. Similar modules have also been created with the same problem. I notice even for a ~800 node website, the search can sometimes timeout and then you don't even get the basic 404 message.
<?php
$output = '';
$no = array('dump','zip','avi','a','of','the','pdf','ppt','doc','rtf','node');
$uri = urldecode(basename(request_uri()));
$keys = split("[^A-Za-z]+", $uri);
$keys = array_diff($keys, $no);
$keys = trim(implode(" ", $keys));
if ($keys) {
$results = search_data($keys);
if ($results) {
$output .= "<p>For your convenience, a search was performed using the query '<i>$keys</i>':</p>";
$output .= $results;
}
else {
$output .= "<p>A search was performed for '<i>$keys</i>', but nothing was found.</p>";
}
$output .= '<p>Use the search form below to continue searching,
access the <a href="/search">advanced search</a>,
or <a href="/feedback">contact us</a> directly.</p>';
$output .= '<form action="search" method="post">
<div id="search">
<input class="form-text" type="text" size="15"
value="" name="keys" /><input class="form-submit"
type="submit" value="search" />
</div></form>';
}
print $output;
?>

Post new comment