A Simple PHP Search Engine Tutorial.

In the process of making the “pwn3d zite” I wanted to add a search capability to the site, so that led me to create this very simple tutorial that covers how to make a PHP search engine for your site. Search engines can range from very simple (the one we’re about to do) or something a bit more complex like [Google]. This tutorial assumes that all the data you want to search resides in a MYSQL database. I should say that there are tons of way on how you could build a search engine, but like the title implies this is the basics on how you could do it, and something you could build on…so lets get started
The search engine that we’re about to build is for a site containing articles, (what kind of articles you may ask, well the topic is irrelevant…), so first we start by creating our table, for this I’m assuming you already created the database.

Creating the Table.

The create table script

CREATE TABLE artcles (
id INT(4) not null primary key auto_increment,
a_title VARCHAR(200) not null,
a_date DATE not null,
a_content TEXT not null,
a_url VARCHAR(200) not null
);

well this create table is self explanatory, but we’ll go over just in case; the table contains 5 columns, first column is the row `id` as you can see all columns are set to not null, so they can’t containing null values, the next is the article title `a_title` column and it contains the title of the article or post, the next column contains the date `a_date`, the fourth column contains the content of the article, and has a data type of TEXT so you can insert your whole article if you like, or you could only insert part of it, chances are the search string use for searching your site most probably will be contained within portion of the article (as a side note: keep in mind that the more data you insert the longer it takes for the database to retrieve it, so as your database grows is really important to optimize your queries so you output the data faster), and last the url `a_url` pointing to the page of the article.

Inserting Data in Table.

Next we’ll insert some test data so we can search our mysql database.

INSERT INTO articles VALUES (1, ‘Pentesting Web Servers’, ‘2009-09-19’,
‘for this tutorial I use some of the tools used most often for pentesting web server and web application; open source tools.’, ‘http://localhost/pentest_server.html’),
(2, ‘Foremost Digital Forensics’, ‘2009-09-19’, ‘Digital Forensics is a relative new discipline that has captivated my attention.’, ‘http://localhost/dforensic.html’);

Creating the Search Form.

Copy this script and open a new notepad instance paste it and name it search.html, or optionally you could insert it in your web page

<h2>Search</h2>
<form name=”search” method=”post” action=”search.php”>
Seach for: <input type=”text” name=”find” />
<input type=”submit” name=”search” value=”Search” />
</form>

take a look at the search form in the following figure.

The PHP Search Script.

Now is where it gets better, we get to do the actual PHP script that is responsible for all the searching. Notice that when you name your PHP script, it has to be the same name as reflected in the action=”search.php” part of the html search form above.

The php script:

<html>
<body>
<?php
//declaring variable
$input = $_POST[‘find’];

//If they did not enter a search term we give them an error
if ($input == “”)
{
echo “<p><h3>You forgot to enter a search term!</h3>”;
exit;
}

//open connection
$conn = mysql_connect(“localhost”, “user”, “password”) or die(mysql_error());
//select database
mysql_select_db(“database”, $conn);

//filtering input for xss and sql injection
$input = strip_tags( $input );
$input = mysql_real_escape_string( $input );
$input = trim( $input );

//the sql statement
$sql = “SELECT * FROM articles WHERE a_title LIKE ‘%$input%’ OR a_content LIKE ‘%$input%'”;

//execute the statement
$data = mysql_query($sql, $conn) or die(mysql_error());
while ($result = mysql_fetch_array($data)) {
//giving names to the fields
$title = $result[‘title’];
$date = $result[‘date’];
$info = $result[‘info’];
$url = $result[‘url’];
//put the results on the screen
echo “<br><b>$title</b>”;
echo ” “;
echo “<b>$date</b><br>”;
echo “$info<br>”;
echo “<a href=$url>$url</a><br>”;
}
//This counts the number or results – and if there wasn’t any it gives a little message explaining that
$anymatches=mysql_num_rows($data);
if ($anymatches == 0)
{
echo “<h3>Results</h3>”;
echo “<p>Sorry, your search: &quot;” . $input . “&quot; returned zero results</p>”;

//Search on google
echo “<p><a href=\”http://www.google.com/search?q=”
. $input . “\” target=\”_blank\” title=\”Look up
” . $input . ” on Google\”>Click here</a> to try the
search on google</p>”;
}

//And we remind them what they searched for
echo “<br><b>You searched for:</b> ” .$input
?>
</body>
</html>

Breaking it down:

if ($input == “”)
{
echo “<p><h3>You forgot to enter a search term!</h3>”;
exit;
}

This section of the string checks to see if a search was actually entered if nothing was entered the echo “<p><h3>You forgot to enter a search term!</h3>”; is executed and the script terminates. If this section of the script is omitted and the user enter a blank search the entire content of the table would be returned back to the user

//open connection
$conn = mysql_connect(“localhost”, “user”, “password”) or die(mysql_error());
//select database
mysql_select_db(“database”, $conn);

This piece of code open the connection to our mysql server, using the mysql administrator credentials, and select the database.

//filtering input for xss and sql injection
$input = strip_tags( $input );
$input = mysql_real_escape_string( $input );
$input = trim( $input );

Next we do some input filtering for Cross Site Scripting using strip_tags( ); function, if we ommit this section and we input something like: <sctipt>javascript:alert(“PCtechtips”);</script> in the search box we can see that our application is vulnerable to XSS. The mysql_real_escape_string( $input ); function filters for sql injection, and you could try omitting this one and input something like ‘ or ‘1=1– you would get the entire content of the table back as the previous string always evaluates to true as shown in the next figure. And finally the trim( $input ); function which eliminates any blank spaces that the user might accidentally enter after the search string.

//the sql statement
$sql = “SELECT * FROM articles WHERE a_title LIKE ‘%$input%’ OR a_content LIKE ‘%$input%'”;

This is the section of our script that actually does the searching against our database, we search for all data WHERE field the user wants is LIKE the search string. We use the % on both side of our variable to indicate that we are not only looking for that specific string but any term containing that string

$data = mysql_query($sql, $conn) or die(mysql_error());

This line actually executes the query

while ($result = mysql_fetch_array($data)) {
//giving names to the fields
$title = $result[‘title’];
$date = $result[‘date’];
$info = $result[‘info’];
$url = $result[‘url’];
//put the results on the screen
echo “<br><b>$title</b>”;
echo ” “;
echo “<b>$date</b><br>”;
echo “$info<br>”;
echo “<a href=$url>$url</a><br>”;
}

This portion of the code starts a loop that cycles through the data and returns it back to the users.

//This counts the number or results – and if there wasn’t any it gives a little message explaining that
$anymatches=mysql_num_rows($data);
if ($anymatches == 0)
{
echo “<h3>Results</h3>”;
echo “<p>Sorry, your search: &quot;” . $input . “&quot; returned zero results</p>”;
}

This part  counts the number of rows that the query returns, and if the count is equal to zero it lets the user know that

//Search on google
echo “<p><a href=\”http://www.google.com/search?q=”
. $input . “\” target=\”_blank\” title=\”Look up
” . $input . ” on Google\”>Click here</a> to try the
search on google</p>”;
}

This section passes the search string to Google once you click on the link

//And we remind them what they searched for
echo “<br><b>You searched for:</b> ” .$input
?>

and last we remind the user what they searched for.

hope you enjoyed the tutorial, and happy searching.

by
Jorge L. Vazquez
Click Here! to Download 10,000 Fonts

Share This!

Leave a Reply

Your email address will not be published.