Welcome, Guest. Please login or register.
March 17, 2010, 09:41:41 PM

Login with username, password and session length
Search:     Advanced search
Wollen Sie dem Website Baker Team beitreten?
Nähere Informationen finden Sie unter hier und auf unserer neuen Webseite .
110308 Posts in 15930 Topics by 9286 Members
Latest Member: lorbas
* Home Help Search Login Register
+  WebsiteBaker Community Forum
|-+  English
| |-+  Droplets (PHP code for use with Droplet module) & Snippets (raw PHP code) (Moderators: Argos, BerndJM)
| | |-+  Searchbox with suggestions
Pages: [1] Go Down Print
Author Topic: Searchbox with suggestions  (Read 623 times)
crnogorac081

Offline Offline

Posts: 1159



« on: January 29, 2010, 07:32:58 PM »

Hi,

here is tutorial how to make a seaarch box with suggestions

First, take a look at the demo , try the search..

I used page_title for sugestions, but you can use any field you want.. For example if you populate keywords, or description fields for each(or some) pages, you can generate sugestions based on those fields..

How to make it:
1. Make a new php file in your root and name it suggestion.php and insert this code:

Quote
<?php
// First we prevent direct access
if(!isset($_POST['queryString'])) {
// nowwe redirect to index, if you are in subfolder use ../index.php
header( 'Location: index.php' ) ;
} else {
    // Now we set the path to config file
    require('config.php');
       
    global $database;
    global $wb;

    if(isset($_POST['queryString'])) {

//        $queryString = $_POST['queryString'];
$queryString = htmlspecialchars($_POST['queryString'], ENT_QUOTES);

        // I used page_title field from pages. you can set or remove limit -- max number of sugestions
        $query = $database->query("SELECT * FROM `".TABLE_PREFIX."pages` WHERE `page_title` LIKE '%$queryString%' LIMIT 20");
        if($query->numRows()  < 1) {
            // replace this text with: there is no suggestion, or whaatever
            echo '&nbsp;&nbsp;&nbsp;No suggestions';    
        } else {
            // now we can add some text like Here are suggestions
            echo '<span style="display:block; font-weight: bold; font-size: 80%; padding: 5px 5px; text-decoration: underline;">Prijedlozi:</span>';
            // now we loop thrue suggestions. style list via droplet
            echo '<ul>';
                    while ($result = $query->fetchRow()) {
                    $filename = str_replace(' ', '', strtolower($result['description']));
                        echo '<li onClick="fill(\''.addslashes($result['description']).'\');"><a href="'.WB_URL.PAGES_DIREC TORY.$result['link'].PAGE_EXTENSION.'">'.$result['page_title'].'</a></li>';
                        }
            echo '</ul>';
        }
    }
} // this ends else statement from the top of the page
?>

2. Make a droplet [[search]] (or name it whatever if you already have this droplet):

Quote
global $TEXT;
$return_value = " ";
if(SHOW_SEARCH) {
$scripta = "\n".'<script type="text/javascript">'."\n";
$scripta .= '    function lookup(inputString) {    '."\n";
$scripta .= '    if(inputString.length < 1) {    '."\n";  // after how menu letters script will react
$scripta .= '    $(\'#suggestions\').hide();    '."\n";
$scripta .= '    } else {    '."\n";
$scripta .= '    $.post("'.WB_URL.'/suggestion.php", {queryString: ""+inputString+""}, function(data){    '."\n";
$scripta .= '    if(data.length > 0) {    '."\n";
$scripta .= '    $(\'#suggestions\').show();    '."\n";
$scripta .= '    $(\'#autoSuggestionsList\').html(data);    '."\n";
$scripta .= '    }    '."\n";
$scripta .= '    });    '."\n";
$scripta .= '    }    '."\n";
$scripta .= '    }    '."\n";
$scripta .= '    function fill(thisValue) {    '."\n";
$scripta .= '    $(\'#inputString\').val(thisValue);    '."\n";
$scripta .= '    setTimeout("$(\'#suggestions\').hide();", 200);    '."\n";
$scripta .= '    }    '."\n";
$scripta .= '</script>    '."\n";
$scripta .= '<style type="text/css">'."\n";
$scripta .= '.suggestionsBox {    '."\n";
$scripta .= '    position: relative; '."\n";
$scripta .= '    left: 80px;    '."\n";
$scripta .= '    margin: 0px 0px 0px 0px;    '."\n";
$scripta .= '    width: 170px;    '."\n";
$scripta .= '    background-color: #fff;    '."\n";
$scripta .= '    -moz-border-radius: 7px;    '."\n";
$scripta .= '    -webkit-border-radius: 7px;    '."\n";
$scripta .= '    border: 2px solid #424242;    '."\n";
$scripta .= '    color: #333;    '."\n";
$scripta .= '}    '."\n";
$scripta .= '.suggestionList ul {    '."\n";
$scripta .= '    margin: 0px;    '."\n";
$scripta .= '    padding: 0px;    '."\n";
$scripta .= '    list-style-type: none;    '."\n";
$scripta .= '}    '."\n";
$scripta .= '.suggestionList li {    '."\n";
$scripta .= '    margin: 0px 0px 3px 0px;    '."\n";
$scripta .= '    padding: 3px;    '."\n";
$scripta .= '    cursor: pointer;     '."\n";
$scripta .= '}    '."\n";
$scripta .= '.suggestionList li:hover {    '."\n";
$scripta .= '     background-color: #f3f3f3;    '."\n";
$scripta .= '}    '."\n";
$scripta .= '</style>    '."\n";

$wb_page_data = str_replace('</head>',$scripta."\n".'</head>', $wb_page_data );

    $return_value  = '<form id="searchform" action="'.WB_URL.'/search/index'.PAGE_EXTENSION.'" method="post" >';
    $return_value  .= '<input class="button" name="dugme" type="submit" value=" " />';
    $return_value  .= '<input class="text" type="text" name="string" id="inputString" onkeyup="lookup(this.value);" onblur="fill();" /> ';
    $return_value  .= '</form>';
    $return_value  .= '<div class="suggestionsBox" id="suggestions" style="display: none;">';
    $return_value  .= '    <div class="suggestionList" id="autoSuggestionsList">';
    $return_value  .= '    </div>';
    $return_value  .= '</div>';
}
return $return_value;

You can restyle list with css inside drplet.

There are a lot of comments if you want to use this module for some other projects..

If you put sugestion.php file inside some folder, you must change path to config.php file in sugestion.pp file, and the path to suggestion.php file inside droplet..


Comments are welcome
have fun Smiley
« Last Edit: February 02, 2010, 11:12:17 AM by crnogorac081 » Logged

Wow, I coded something myself: PM Messanger Modul ,Searchbox with suggestions
pcwacht
Development Team
******
Online Online

Posts: 2190


WWW
« Reply #1 on: January 29, 2010, 08:25:14 PM »

Demo looks neat

Will sure have a look at it.
Thanks.

John
Logged

seagull

Online Online

Posts: 61


« Reply #2 on: January 29, 2010, 09:34:40 PM »

Used the code and the droplet, works ok! cheesy

First i overlooked the one "g" in the filename sugestion.php, i saved it first as suggestion.php
But for the rest, nice job.

Jan
Logged
crnogorac081

Offline Offline

Posts: 1159



« Reply #3 on: January 29, 2010, 09:52:20 PM »

lol I misspelled it Cheesy but Im glad it works and that you liked it Smiley I also added some opacity on demo site Smiley

= I corrected one g Smiley
« Last Edit: January 29, 2010, 09:57:17 PM by crnogorac081 » Logged

Wow, I coded something myself: PM Messanger Modul ,Searchbox with suggestions
DarkViper

Offline Offline

Posts: 182


« Reply #4 on: February 02, 2010, 01:10:37 AM »

The module works as planned.

Yet here I am forced to issue a Security Warning!

The script 'suggestion.php' is insecure and an optimal target for SQL-Injections.
Each only halfway decent hacker, is thus in a position to change the database or delete them completely.

@ crnogorac081:: Please revise the parameter passing, so that no more undesirable values can reach the script.

Werner
( QA-Team )
Logged

1984 was not meant as an instruction manual !!
crnogorac081

Offline Offline

Posts: 1159



« Reply #5 on: February 02, 2010, 01:23:28 AM »

I am not a coder, could you please help how to improve this from hacking ?

Logged

Wow, I coded something myself: PM Messanger Modul ,Searchbox with suggestions
crnogorac081

Offline Offline

Posts: 1159



« Reply #6 on: February 02, 2010, 01:44:32 AM »

Ok,

if I replace

$queryString = $_POST['queryString'];

with

$queryString = htmlspecialchars($_POST['queryString'], ENT_QUOTES);

did I solved the problem ?
Logged

Wow, I coded something myself: PM Messanger Modul ,Searchbox with suggestions
DarkViper

Offline Offline

Posts: 182


« Reply #7 on: February 02, 2010, 01:56:00 AM »

i can give you a 'quick&dirty' solution:

Code:
$queryString = $_POST['queryString'];
if( preg_match('/;|UPDATE|DROP|DELETE|ALTER|\<SCRIPT.*\>|eval\(/si', $queryString)
{
    echo '&nbsp;&nbsp;&nbsp;Forbidden Request!!';
}
else
{
....

HTML-Entities are not the problem...except "<script...>...</script>. At max they can destroy the design for one view, nothing more. But you must proof that no modified or extended SQL-Statement can be executed. Much important: NEVER a semicolon should appear in the LIKE-clause. It would cancel the current SQL query and possibly execute others, which was added after the semicolon.
« Last Edit: February 02, 2010, 11:12:16 AM by DarkViper » Logged

1984 was not meant as an instruction manual !!
crnogorac081

Offline Offline

Posts: 1159



« Reply #8 on: February 02, 2010, 02:05:17 AM »

cool tnx,

but will this also prevent attack ?

$queryString = htmlspecialchars($_POST['queryString'], ENT_QUOTES);

I belive with this code you cant modify SQL request as it will dissable special character, right ?
Logged

Wow, I coded something myself: PM Messanger Modul ,Searchbox with suggestions
DarkViper

Offline Offline

Posts: 182


« Reply #9 on: February 02, 2010, 02:25:37 AM »

Example for a SQL-Injection:

original query (after replace variables)
$queryString = 'dingdong';
SELECT * FROM `wb1_pages` WHERE `page_title` LIKE '%dingdong%' LIMIT 20")

a injected query:

$queryString = '\';DELETE FROM `wb1_pages`;';
SELECT * FROM `wb1_pages` WHERE `page_title` LIKE '%';DELETE FROM `wb1_pages`;%' LIMIT 20")

try this.. and your pages-table will be empty..  evil
« Last Edit: February 02, 2010, 02:27:49 AM by DarkViper » Logged

1984 was not meant as an instruction manual !!
crnogorac081

Offline Offline

Posts: 1159



« Reply #10 on: February 02, 2010, 10:12:05 AM »

Well I just tested your quoery on my live site and inserted this :

'\';DELETE FROM `ul_pages`;';

into searchbox, and table is still there Smiley so there is no SQL hack..

But, yestrday I added htmlspecialchars func. to

$queryString = htmlspecialchars($_POST['queryString'], ENT_QUOTES);

So now it is ok for general use ?
Logged

Wow, I coded something myself: PM Messanger Modul ,Searchbox with suggestions
doc

Offline Offline

Posts: 3579


« Reply #11 on: February 02, 2010, 10:14:57 AM »

@crnogorac081: Most likely because your server has magic_quotes_gpc enabled. This option automatically escapes critical characters from get, post, cookie array. Servers without this setting however would be vulnerable to the SQL injection posted by DarkViper.

Doc
Logged
crnogorac081

Offline Offline

Posts: 1159



« Reply #12 on: February 02, 2010, 10:49:49 AM »

@doc

Will this code: $queryString = htmlspecialchars($_POST['queryString'], ENT_QUOTES);  work to prevent DB hack on servers where magic quotes are disabled ?

If this code want work, please point me to the right direction..

« Last Edit: February 02, 2010, 10:52:29 AM by crnogorac081 » Logged

Wow, I coded something myself: PM Messanger Modul ,Searchbox with suggestions
DarkViper

Offline Offline

Posts: 182


« Reply #13 on: February 02, 2010, 11:18:38 AM »

'\';DELETE FROM `ul_pages`;';
into searchbox, and table is still there Smiley so there is no SQL hack..
This was an extremely simple try... be sure, there are much more posibillities...

last night i posted a first solution for your prob..
Logged

1984 was not meant as an instruction manual !!
crnogorac081

Offline Offline

Posts: 1159



« Reply #14 on: February 02, 2010, 11:25:38 AM »

ok, but what if I have page_title named: Update or Updated, Alter Ego, or any word containing UPDATE, DROP, DELETE, ALTER or SCRIPT..

will your code print: Forbiden request ?
Logged

Wow, I coded something myself: PM Messanger Modul ,Searchbox with suggestions
crnogorac081

Offline Offline

Posts: 1159



« Reply #15 on: February 03, 2010, 12:04:45 PM »

Also I tried this code to add slashes to DB call:

Code:
// Include WB functions file
        require_once(WB_PATH.'/framework/functions.php');

AND THEN:

$queryString = $wb->add_slashes($_POST['queryString']);

but then script want work.. does anyone know why ?
« Last Edit: February 03, 2010, 12:42:06 PM by crnogorac081 » Logged

Wow, I coded something myself: PM Messanger Modul ,Searchbox with suggestions
crnogorac081

Offline Offline

Posts: 1159



« Reply #16 on: February 04, 2010, 10:08:50 PM »

[[refresh]]  grin
Logged

Wow, I coded something myself: PM Messanger Modul ,Searchbox with suggestions
Pages: [1] Go Up Print 
Jump to:  

Powered by MySQL Powered by PHP Powered by SMF 1.1.11 | SMF © 2006-2009, Simple Machines LLC Valid XHTML 1.0! Valid CSS!