PHP CookBook Free Open Book

PHP CookBook

Previous Section Next Section

Recipe 19.14 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 = '#<!-- search-start -->(.*' . preg_quote($_REQUEST['term'],'#'). 
              '.*)<!-- search-end -->#Sis';

If you don't want the search term to match text that's inside HTML or PHP tags in your pages, add a call to strip_tags( ) to the code that loads the contents of the file for searching:

// load the contents of the file into $file
$file = strip_tags(join('',file($path)));
Example 19-5. site-search.php
function pc_search_dir($dir) { 
    global $body_regex,$title_regex,$seen;

    // array to hold pages that match
    $pages = array();

    // array to hold directories to recurse into
    $dirs = array();

    // mark this directory as seen so we don't look in it again
    $seen[realpath($dir)] = true;
    
    // if we can get a directory handle for this directory
    if (is_readable($dir) && ($d = dir($dir))) {
        // get each file name in the directory
        while (false !== ($f = $d->read())) {
            // build the full path of the file
            $path = $d->path.'/'.$f;
            // if it's a regular file and we can read it
            if (is_file($path) && is_readable($path)) {
                
                $realpath = realpath($path);
                // if we've seen this file already,
                if ($seen[$realpath]) {
                    // then skip it
                    continue;
                } else {
                    // otherwise, mark it as seen so we skip it
                    // if we come to it again
                    $seen[$realpath] = true;
                }

                // load the contents of the file into $file
                $file = join('',file($path));

                // if the search term is inside the body delimiters
                if (preg_match($body_regex,$file)) {

                    // construct the relative URI of the file by removing
                    // the document root from the full path
                    $uri = substr_replace($path,'',0,strlen($_SERVER['DOCUMENT_ROOT']));

                    // If the page has a title, find it
                    if (preg_match('#<title>(.*?)</title>#Sis',$file,$match)) {
                        // and add the title and URI to $pages
                        array_push($pages,array($uri,$match[1]));
                    } else {
                        // otherwise use the URI as the title
                        array_push($pages,array($uri,$uri));
                    }
                }
            } else {
                // if the directory entry is a valid subdirectory
                if (is_dir($path) && ('.' != $f) && ('..' != $f)) {
                    // add it to the list of directories to recurse into
                    array_push($dirs,$path);
                }
            }
        }
        $d->close();
    }

    /* look through each file in each subdirectory of this one, and add
       the matching pages in those directories to $pages. only look in
       a subdirectory if we haven't seen it yet.
    */
    foreach ($dirs as $subdir) {
        $realdir = realpath($subdir);
        if (! $seen[$realdir]) {
            $seen[$realdir] = true;
            $pages = array_merge($pages,pc_search_dir($subdir));
        }
    }

    return $pages;
}

// helper function to sort matched pages alphabetically by title
function pc_page_sort($a,$b) {
    if ($a[1] == $b[1]) {
        return strcmp($a[0],$b[0]);
    } else {
        return ($a[1] > $b[1]);
    }
}

// array to hold the pages that match the search term
$matching_pages = array();
// array to hold pages seen while scanning for the search term
$seen = array();
// directories underneath the document root to search
$search_dirs = array('sports','movies','food');
// regular expression to use in searching files. The "S" pattern
// modifier tells the PCRE engine to "study" the regex for greater
// efficiency.
$body_regex = '#<body>(.*' . preg_quote($_REQUEST['term'],'#'). 
              '.*)</body>#Sis';

// add the files that match in each directory to $matching pages
foreach ($search_dirs as $dir) {
    $matching_pages = array_merge($matching_pages,
                                  pc_search_dir($_SERVER['DOCUMENT_ROOT'].'/'.$dir));
}

if (count($matching_pages)) {
    // sort the matching pages by title
    usort($matching_pages,'pc_page_sort');
    print '<ul>';
    // print out each title with a link to the page
    foreach ($matching_pages as $k => $v) {
        print sprintf('<li> <a href="%s">%s</a>',$v[0],$v[1]);
    }
    print '</ul>';
} else {
    print 'No pages found.';
}


    Previous Section Next Section
    Index: [SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T][U][V][W][X][Z]


         Main Menu
    Main Page
    Table of content
    Copyright
    Preface
    Chapter 1. Strings
    Chapter 2. Numbers
    Chapter 3. Dates and Times
    Chapter 4. Arrays
    Chapter 5. Variables
    Chapter 6. Functions
    Chapter 7. Classes and Objects
    Chapter 8. Web Basics
    Chapter 9. Forms
    Chapter 10. Database Access
    Chapter 11. Web Automation
    Chapter 12. XML
    Chapter 13. Regular Expressions
    Chapter 14. Encryption and Security
    Chapter 15. Graphics
    Chapter 16. Internationalization and Localization
    Chapter 17. Internet Services
    Chapter 18. Files
    Chapter 19. Directories
    19.1 Introduction
    Recipe 19.2 Getting and Setting File Timestamps
    Recipe 19.3 Getting File Information
    Recipe 19.4 Changing File Permissions or Ownership
    Recipe 19.5 Splitting a Filename into Its Component Parts
    Recipe 19.6 Deleting a File
    Recipe 19.7 Copying or Moving a File
    Recipe 19.8 Processing All Files in a Directory
    Recipe 19.9 Getting a List of Filenames Matching a Pattern
    Recipe 19.10 Processing All Files in a Directory
    Recipe 19.11 Making New Directories
    Recipe 19.12 Removing a Directory and Its Contents
    Recipe 19.13 Program: Web Server Directory Listing
    Recipe 19.14 Program: Site Search
    Chapter 20. Client-Side PHP
    Chapter 21. PEAR
    Colophon
    Index


    More Books
    PHP Hacks
    Processing Xml With Java - A Guide To Sax, Dom, Jdom, Jaxp, And Trax
    The Koran (Holy Qur'an)
    Macromedia Flash 8 Bible
    Search Engine Optimization for Dummies
    YouTube Traffic
    PHP 5 for Dummies
    Harry Potter and The Chamber of Secrets
    Harry Potter and the Sorcerer's Stone
    The Pilgrim's Progress
    Wireless Hacks
    Flash Hacks. 100 Industrial-Strength Tips & Tools
    PayPal Hacks. 100 Industrial-Strength Tips and Tools
    Amazon Hacks
    Pdf Hacks
    The Da Vinci Code
    Google Hacks
    The Holy Bible
    Windows XP For Dummies
    Harry Potter and the Half-Blood Prince
    Seo Book
    Upgrading and Repairing Networks
    Macromedia Dreamweaver 8 UNLEASHED
    Windows XP Annoyances
    Windows XP Hacks
    Microsoft Windows XP Power Toolkit
    Teach Yourself MS Office In 24Hours
    iPod & iTunes Missing Manual
    PC Hacks 100 Industrial-Strength Tips and Tools
    PC Overclocking, Optimization, and Tuning - 2th Edition
    PC Hardware In A Nutshell 3rd Edition
    PC Hardware in a Nutshell, 2nd Edition
    Upgrading and Repairing PCs
    Google for Dummies
    MySQL Cookbook
    Teach Yourself Macromedia Flash 8 In 24 Hours
    PHP CookBook
    Sams Teach Yourself JavaScript in 24 Hours
    PHP5 Manual
    Free Games Paper Airplanes
    500 Juegos Gratis 500 Giochi Gratis 500 Jeux Gratuits 500 Jogos Gratis 500 Kostenlose Spiele