19.13. Program: Site Search

You can use site-search.php, shown in Example 19-5, as a search engine for a small-to-medium size, file-based site.

The program looks for a search term (in $_REQUEST['term']) in all files within a specified set of directories under the document root. Those directories are set in $search_dirs. It also recurses into subdirectories and follows symbolic links but keeps track of which files and directories it has seen so that it doesn’t get caught in an endless loop.

If any pages are found that contain the search term, it prints list of links to those pages, alphabetically ordered by each page’s title. If a page doesn’t have a title (between the <title> and </title> tags), the page’s relative URI from the document root is used.

The program looks for the search term between the <body> and </body> tags in each file. If you have a lot of text in your pages inside <body> tags that you want to exclude from the search, surround the text that should be searched with specific HTML comments and then modify $body_regex to look for those tags instead. Say, for example, if your page looks like this:

<body>

// Some HTML for menus, headers, etc.

<!-- search-start -->

<h1>Aliens Invade Earth</h1>

<h3>by H.G. Wells</h3>

<p>Aliens invaded earth today. Uh Oh.</p>

// More of the story

<!-- search-end -->

// Some HTML for footers, etc.

</body>

To match the search term against just the title, author, and story inside the HTML comments, change $body_regex to:

$body_regex = ...

Get PHP Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.