Wednesday, April 25, 2012

PHP: how to create a search form that will link to my search script

I have a PHP search script which I've altered slightly and works well for me. But there is one part Im not sure how to do, and that is linking the script up to a search form, that a user can complete.



The script is below, and it searches a text file for key words. Currently the "key word" is entered directly into the script. But that is no good for someone visiting my site - so I wanted to create a search form. But not sure if I should use POST or GET or something else. And I dont know how I should link the code up from the form, to the script below. I've searched for quite a bit of time to find this, but cant see anything that covers it, and my attempts at getting it to link up arent going well. If anyone could help it would be most appreciated.



(original code borrowed from Lekensteyn - http://stackoverflow.com/a/3686246/1322744 (thanks))



<?php
$file = 'users.txt';
$searchfor = 'entersearchterm';

$contents = file_get_contents($file);
$pattern = preg_quote($searchfor, '/');
$pattern = "/^.*$pattern.*\$/m";

if(preg_match_all($pattern, $contents, $matches)){
echo "Found matches:<br />";
echo implode("<br />", $matches[0]);
}
else{
echo "No matches found";
fclose ($file);
}
?>




No comments:

Post a Comment