InfinityQuest - Programming Code Tutorials and Examples with Python, C++, Java, PHP, C#, JavaScript, Swift and more

Menu
  • Home
  • Sitemap

Python Programming Language Best Tutorials and Code Examples

Learn Python Right Now!
Home
PHP
Program: Site Search in PHP
PHP

Program: Site Search in PHP

InfinityCoder December 26, 2016

You can use site-search.php as a search engine for a small-to-medium, file-based, site:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
class SiteSearch {
   public $bodyRegex = '';
   protected $seen = array();
 
   public function searchDir($dir) {
      // 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
      $this->seen[realpath($dir)] = true;
 
      try {
          foreach (new RecursiveIteratorIterator(
          new RecursiveDirectoryIterator($dir)) as $file) {
             if ($file->isFile() && $file->isReadable() &&
          (! isset($this->seen[$file->getPathname()]))) {
             // mark this as seen so we skip it
             // if we come to it again
             $this->seen[$file->getPathname()] = true;
 
             // load the contents of the file into $text
             $text = file_get_contents($file->getPathname());
 
             // if the search term is inside the body delimiters
             if (preg_match($this->bodyRegex,$text)) {
 
             // construct the relative URI of the file by removing
             // the document root from the full path
             $uri = substr_replace($file->getPathname(),'',0,strlen
             ($_SERVER['DOCUMENT_ROOT']));
 
             // if the page has a title, find it
             if (preg_match('#<title>(.*?)</title>#Sis',$text,$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));
             }
          }
          }
       }
    } catch (Exception $e) {
         // There was a problem opening the directory
    }
    return $pages;
  }
}
// helper function to sort matched pages alphabetically by title
function by_title($a,$b) {
        return ($a[1] == $b[1]) ?
                strcmp($a[0],$b[0]) :
               ($a[1] > $b[1]);
}
// SiteSearch object to do the searching
$search = new SiteSearch();
 
// array to hold the pages that match the search term
$matching_pages = 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.
$search->bodyRegex = '#<body>(.*' . preg_quote($_GET['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,
                       $search->searchDir($_SERVER['DOCUMENT_ROOT'].'/'.$dir));
}
 
if (count($matching_pages)) {
  // sort the matching pages by title
  usort($matching_pages,'by_title');
  // print out each title with a link to the page
  foreach ($matching_pages as $k => $v) {  
     print '<ul>';
  }
     print '</ul>';
} else {
     print 'No pages found.';
}

The program looks for a search term (in $_GET[‘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 a 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.

If your page looks like what is shown here:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<html>
<head>
       <title>Your Title</title>
</head>
<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>
</html>

to match the search term against just the title, author, and story inside the HTML comments, change $search->bodyRegex to this:

1
2
$search->bodyRegex = '#<!-- search-start -->(.*' . preg_quote($_GET['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, as shown:

1
2
// load the contents of the file into $text
$text = strip_tags(file_get_contents($file->getPathname()));

 

Share
Tweet
Email
Prev Article
Next Article

Related Articles

Integrating with JavaScript in PHP
You want part of your page to update with server-side …

Integrating with JavaScript in PHP

Calling Variable Functions in PHP
You want to call different functions depending on a variable’s …

Calling Variable Functions in PHP

About The Author

InfinityCoder
InfinityCoder

Leave a Reply

Cancel reply

Recent Tutorials InfinityQuest

  • Adding New Features to bash Using Loadable Built-ins in bash
    Adding New Features to bash Using Loadable …
    June 27, 2017 0
  • Getting to the Bottom of Things in bash
    Getting to the Bottom of Things in …
    June 27, 2017 0

Recent Comments

  • fer on Turning a Dictionary into XML in Python
  • mahesh on Turning a Dictionary into XML in Python

Categories

  • Bash
  • PHP
  • Python
  • Uncategorized

InfinityQuest - Programming Code Tutorials and Examples with Python, C++, Java, PHP, C#, JavaScript, Swift and more

About Us

Start learning your desired programming language with InfinityQuest.com.

On our website you can access any tutorial that you want with video and code examples.

We are very happy and honored that InfinityQuest.com has been listed as a recommended learning website for students.

Popular Tags

binary data python CIDR convert string into datetime python create xml from dict python dictionary into xml python how to create xml with dict in Python how to write binary data in Python IP Address read binary data python tutorial string as date object python string to datetime python

Archives

  • June 2017
  • April 2017
  • February 2017
  • January 2017
  • December 2016
  • November 2016
Copyright © 2021 InfinityQuest - Programming Code Tutorials and Examples with Python, C++, Java, PHP, C#, JavaScript, Swift and more
Programming Tutorials | Sitemap