<?
// Erik J. Barzeski's 404 Search Code
// As used on The Sand Trap .com and discussed at:
// http://nslog.com/archives/2003/02/24/404_search_function.php
// http://nslog.com/archives/2003/02/26/404_search_function_code.php
// 
// You are free to copy and use this code anywhere you see fit
// so long as the above text remains in the file as it is here


// Get the actual name of the file referenced in the URL
$search_term substr$_SERVER["REQUEST_URI"], );
$pieces explode'/'$search_term );
$search_term $pieces[count($pieces) - 1];

// Get rid of bad websites that think I'm running IIS
if(    strstr($search_term'.dll') ||
    
strstr($search_term'.asp') ||
    
strstr($search_term'.exe')
    ) exit;

// Don't need the file extension unless looking for images
$pieces explode'.'$search_term );
$search_term $pieces[0];
$extension $pieces[1];

// No translated URL, so do a search for this term instead
$search_url 'http://thesandtrap.com/cgi-bin/mt-search.cgi?IncludeBlogs=1&amp;search=';

// If staff is searching for images, put the extension back and don't take out '_'
if ($extension == "jpg" || $extension == "gif" || $extension == "png")
    
$search_term .= ".$extension";
else
    
$search_term str_replace('_''%20'$search_term);

// Create full search URL and perform search
$full_search_url $search_url $search_term;
$full_page implode""file$full_search_url ));

// Email myself to monitor 404 searches
$body_of_email "Search URL: $full_search_url
Queried URL: " 
$_SERVER["REQUEST_URI"] . "
Search Term(s): $search_term_fixed"
;
$clickable_search str_replace('%20'' '$search_term);
@
mail("erik@thesandtrap.com""Search Query: $clickable_search"$body_of_email);

// Find unique URL - TAKE USER TO TRUNCATED FILENAME IF EXISTS
$search_string '/<a href="([^"]*)".*search_result/';
$count preg_match_all($search_string$full_page$matches );

// If there's only one search match, go straight to the match
if( $count == ) {
     
header"Location: {$matches[1][0]}" );
}
// Otherwise, print the results
else {
     echo 
$full_page;
}
?>