Solved Search Feature for HTML

April 3, 2009 at 17:30:25
Specs: Windows Vista, 2GB
Hey, I was just wondering how I could put a search feature into my website, one that only searches the website. If you have an code I would appreciate it. Thank you.

See More: Search Feature for HTML

Report •

April 4, 2009 at 03:30:35
✔ Best Answer
I'm not entirely sure on how the process works, but I think the major search engines take snapshots of websites using the data found in <meta keywords... tags and store it in a database. When a person makes a search, the database is queried.

I may be grasping straws here, but I think you could probably do something similar without a database by using a flat data file. For a crude example, create a plain text file and call it keyw.idx



the format I used is the name of resource, a pound sign as a deliminator, and then keywords that appear within the resource seperated by commas.



   if(isset($_POST["cmd"]) && $_POST["cmd"] === "Search") {

      $hits = 0;
      echo "Search results for " . $_POST["query"] . "<hr align='left' width='300'>";  

      $fh = @fopen("keyw.idx", "r");
      if($fh) {
         if(flock($fh, LOCK_EX)) {
            while(!feof($fh)) {            
               $buf = split("#", fgets($fh));
               if(count($buf) == 2) {
                  $kws = split(",", $buf[1]);
                  for($i=0; $i < count($kws); $i++) {                     

                     if(preg_match('/\b' . $kws[$i] . '\b/i', $_POST["query"]) > 0) {                        
                        echo sprintf("%3d", ++$hits) . " : <a href='$buf[0]'>$buf[0]</a> - $kws[$i]

            flock($fh, LOCK_UN);

            if($hits == 0) {
               echo "The query found 0 matches";

            echo "
<a href='" . $_SERVER["PHP_SELF"] . "'>Back</a>";
   } else {           
<form action="<?php echo $_SERVER["PHP_SELF"];?>" method="post">

Query: <input name="query" size="20" maxlength="64" type="text">
<input name="cmd" value="Search" type="submit">


To try it, place both the keyw.idx file and the search.php file in the same directory. The script is very basic and only handles one keyword, but could probably be expanded with a bit of extra code.


wow; Justin really needs another method for adding code snippits. :P

Report •

April 6, 2009 at 19:48:03
Thank you, that worked. You are a web genius.

Report •

April 6, 2009 at 22:43:25
LOL; I'm hardly a genius, but just a guy willing to try out a few ideas. :P

Glad it helped.

Report •

Related Solutions

April 6, 2009 at 23:18:02
I have another question now, it's already posted and it's
about browser compatibility check; if you know how to do
that, you should read my post, the subject is : "Browser Compatibility."

This is the URL :

Report •

Ask Question