How to make search box work in php

First create form in html file ::

<form id=”search” action=”search.php” method=”GET” accept-charset=”utf-8″>
<input type=”text” value=”” name=”s”>

<a href=”#” onClick=”document.getElementById(‘search’).submit()” class=”btn btn-2″>search <span></span><i class=”icon-chevron-right”></i></a>
</form>

Then create search.php file::

<!DOCTYPE html>
<html lang=”en”>
<head>
<title>Search results</title>
<meta charset=”utf-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<script src=”jquery.js”></script>
<script src=”search.js”></script>

</head>
<body>

<h3>Search result:</h3>
<div id=”search-results”></div>
</body>
</html>

 

Then create result.php file::

<?php

if(!isset($_GET[‘s’])) {
die(‘You must define a search term!’);
}

$highlight = true;//highlight results or not
$search_in = array(‘html’, ‘htm’);//allowable filetypes to search in
$search_dir = ‘..’;//starting directory
$recursive = true;//should it search recursively or not
define(‘SIDE_CHARS’, 80);
$file_count = 0;
$search_term = mb_strtolower($_GET[‘s’], ‘UTF-8’);
//$search_term = $_GET[‘s’];
$search_term_length = strlen($search_term);
$final_result = array();

$files = list_files($search_dir);

foreach($files as $file){
$contents = file_get_contents($file);
preg_match(“/\<title\>(.*)\<\/title\>/”, $contents, $page_title); //getting page title
if (preg_match(“#\<body.*\>(.*)\<\/body\>#si”, $contents, $body_content)){ //getting content only between <body></body> tags
$clean_content = strip_tags($body_content[0]); //remove html tags
$clean_content = preg_replace( ‘/\s+/’, ‘ ‘, $clean_content ); //remove duplicate whitespaces, carriage returns, tabs, etc

//$found = strpos_recursive($clean_content, $search_term);
$found = strpos_recursive(mb_strtolower($clean_content, ‘UTF-8’), $search_term);
$final_result[$file_count][‘page_title’][] = $page_title[1];
$final_result[$file_count][‘file_name’][] = $file;
}
if($found && !empty($found)) {
for ($z = 0; $z < count($found[0]); $z++){
$pos = $found[0][$z][1];
$side_chars = SIDE_CHARS;
if ($pos < SIDE_CHARS){
$side_chars = $pos;
$pos_end = SIDE_CHARS + $search_term_length;
}else{
$pos_end = SIDE_CHARS*2 + $search_term_length;
}

$pos_start = $pos – $side_chars;
$str = substr($clean_content, $pos_start, $pos_end);
//$result = preg_replace(‘#’.$search_term.’#ui’, ‘<span class=”search”></span>’, $str);
$result = preg_replace(‘#’.$search_term.’#ui’, ‘<span class=”search”>’.$search_term.'</span>’, $str);
$final_result[$file_count][‘search_result’][] = $result;
}
} else {
$final_result[$file_count][‘search_result’][] = ”;
}
$file_count++;
}
?>
<!DOCTYPE HTML>
<html lang=”en-US” class=”iframe”>
<head>
<title>Search results</title>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
<link rel=”stylesheet” href=”search.css”>

</head>
<body>
<script>
;(function(){
document.body.onload=resize
window.onresize=resize

function resize(){
parent._resize(document.getElementById(‘search-results’).offsetHeight)
}
})()
</script>

<div id=”search-results”>
<ol class=”search_list”>
<?php
$match_count = 0;
for ($i=0; $i < count($final_result); $i++){
if (!empty($final_result[$i][‘search_result’][0]) || $final_result[$i][‘search_result’][0] !== ”){
$match_count++;
?>
<li>
<h4 class=”search_title”><a target=”_top” href=”<?php echo $final_result[$i][‘file_name’][0]; ?>” class=”search_link”> <?php echo $final_result[$i][‘page_title’][0]; ?> </a></h4>
…<?php echo $final_result[$i][‘search_result’][0]; ?>…
<span class=”match”>Terms matched: <?php echo count($final_result[$i][‘search_result’]); ?> – URL: <?php echo $final_result[$i][‘file_name’][0]; ?></span>
</li>
<?php
}
}
if ($match_count == 0) {
echo ‘<h4>No results found for <span class=”search”>’.$search_term.'</span></h4>’;
}
?>
</ol>
</div>

</body>
</html>
<?php
//lists all the files in the directory given (and sub-directories if it is enabled)
function list_files($dir){
global $recursive, $search_in;

$result = array();
if(is_dir($dir)){
if($dh = opendir($dir)){
while (($file = readdir($dh)) !== false) {
if(!($file == ‘.’ || $file == ‘..’)){
$file = $dir.’/’.$file;
if(is_dir($file) && $recursive == true && $file != ‘./.’ && $file != ‘./..’){
$result = array_merge($result, list_files($file));
}
else if(!is_dir($file)){
if(in_array(get_file_extension($file), $search_in)){
$result[] = $file;
}
}
}
}
}
}
return $result;
}

//returns the extention of a file
function get_file_extension($filename){
$result = ”;
$parts = explode(‘.’, $filename);
if(is_array($parts) && count($parts) > 1){
$result = end($parts);
}
return $result;
}

function strpos_recursive($haystack, $needle, $offset = 0, &$results = array()) {
$offset = stripos($haystack, $needle, $offset);
if($offset === false) {
return $results;
} else {
$pattern = ‘/’.$needle.’/ui’;
preg_match_all($pattern, $haystack, $results, PREG_OFFSET_CAPTURE);
return $results;
}
}
?>

then create search.js file::

$(function(){
var s=location.search.replace(/^\?.*s=([^&]+)/,’$1′)
,form=$(‘#search-form’)
,input=$(‘input[type=text]’,form)
,results=$(‘#search-results’).height(0)
,src=’search/results.php’
,ifr=$(”)

if(results.length)
ifr
.attr({
src:src+’?s=’+s
})
.appendTo(results)
,input
.val(decodeURI(s))

window._resize=function(h){
results
.height(h)
}
})

then have some style to search search.css ::

html, body {
min-width:300px;
height:auto;
background:transparent;
}

body {
overflow:hidden;
}
#search-results{
padding:20px 10px 0px 5px;
overflow:hidden;
}

#search-results iframe html{
border:none;
}
#search-results iframe {
min-width:300px;
}

h4{
font-size: 14px;
line-height: 18px;
color: #cc1014;
display: block;
}
h4 a{color: #cc1014;}
h4 a:hover{color: #26aad0;;}
ol.search_list {
margin-left: 15px;
list-style-type:none;
counter-reset: ol;
}
ol.search_list li:before {
content: counter(ol) “.”;
counter-increment: ol;
float:left;
display:block;
width:20px;
text-align:right;
padding-right:10px;
margin:0px 0px 0 -30px
}
ol.search_list li {
padding-bottom:20px;
margin-left:15px;
}
span.match {
color:#9d261d;
font-size:11px;
display:block;
}
span.search {
color:#9d261d;

}
.search_link{
text-decoration: none;
}
.search_link:hover{
text-decoration: none;
}

This will surely work for searching words from ur website

THANKS 🙂

 

 

Advertisements

5 thoughts on “How to make search box work in php

  1. Vamos a probar.. Ok, si es funcional.. solo tiene un par de errores en: comillas dobles simples y un signo que no es un menos (″ , ‘ , -) y el nombre del archivo result.php es (results.php) pero de resto genial.. Gracias

    Let’s try .. Ok, if functional .. just has a couple of errors: single quotes, and a sign is not a minus (“, ‘, -) and the name of the file is result.php (results. php) but rest great .. Thanks

  2. Hey, this works perfect but I have a request. I would like to implement something like this but I’m currently working with accented words like cafĂ©, monĂłtono, jardĂ­n, etc and when i type for example “cafe” or “CAFÉ” it doesn´t find anything. Any solution?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s