WebsiteBaker Logo
  • *
  • Templates
  • Help
  • Add-ons
  • Download
  • Home
*
Welcome, Guest. Please login or register.

Login with username, password and session length
 

News


WebsiteBaker 2.13.6 is now available!


Will it continue with WB? It goes on! | Geht es mit WB weiter? Es geht weiter!
https://forum.websitebaker.org/index.php/topic,32340.msg226702.html#msg226702


The forum email address board@websitebaker.org is working again
https://forum.websitebaker.org/index.php/topic,32358.0.html


R.I.P Dietmar (luisehahne) and thank you for all your valuable work for WB
https://forum.websitebaker.org/index.php/topic,32355.0.html


* Support WebsiteBaker

Your donations will help to:

  • Pay for our dedicated server
  • Pay for domain registration
  • and much more!

You can donate by clicking on the button below.


  • Home
  • Help
  • Search
  • Login
  • Register

  • WebsiteBaker Community Forum »
  • WebsiteBaker Support (2.8.x) »
  • Droplets & Snippets »
  • Searchbox with suggestions
  • Print
Pages: [1] 2   Go Down

Author Topic: Searchbox with suggestions  (Read 33030 times)

Offline crnogorac081

  • Posts: 2161
  • Gender: Male
Searchbox with suggestions
« on: January 29, 2010, 07:32:58 PM »
Hi,

here is tutorial how to make a seaarch box with suggestions

Requires: JQuery

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;">Suggestions:</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
?>
NOTE: 7th line from below is to long.. So when you copy-paste code you will get PAGES_DIRE C TORY, so you need to remove space in DIRECTORY word..
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 droplet.

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

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


Comments are welcome
have fun :)
« Last Edit: May 02, 2010, 09:47:58 PM by crnogorac081 »
Logged
Web developer

Offline pcwacht

  • Posts: 2923
  • Gender: Male
    • Dutch ICT info
Re: Search box with suggestions
« Reply #1 on: January 29, 2010, 08:25:14 PM »
Demo looks neat

Will sure have a look at it.
Thanks.

John
Logged
http://www.ictwacht.nl = Dutch ICT info
http://www.pcwacht.nl = My first
both still work in progress, since years.....

seagull

  • Guest
Re: Search box with suggestions
« Reply #2 on: January 29, 2010, 09:34:40 PM »
Used the code and the droplet, works ok! :lol:

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

Offline crnogorac081

  • Posts: 2161
  • Gender: Male
Re: Search box with suggestions
« Reply #3 on: January 29, 2010, 09:52:20 PM »
lol I misspelled it :D but Im glad it works and that you liked it :) I also added some opacity on demo site :)

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

Offline DarkViper

  • Forum administrator
  • *****
  • Posts: 3087
  • Gender: Female
Re: Searchbox with suggestions
« 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.
already done..

Werner
( QA-Team )
« Last Edit: March 30, 2010, 02:01:32 AM by DarkViper »
Logged
Der blaue Planet - er ist nicht unser Eigentum - wir haben ihn nur von unseren Nachkommen geliehen

"We need education to cope with digitalization - and NOT the digitalization of education.!"

Tägliches Stoßgebet: Oh Herr, wirf Hirn vom Himmel !

Offline crnogorac081

  • Posts: 2161
  • Gender: Male
Re: Searchbox with suggestions
« 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
Web developer

Offline crnogorac081

  • Posts: 2161
  • Gender: Male
Re: Searchbox with suggestions
« 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
Web developer

Offline DarkViper

  • Forum administrator
  • *****
  • Posts: 3087
  • Gender: Female
Re: Searchbox with suggestions
« Reply #7 on: February 02, 2010, 01:56:00 AM »
i can give you a 'quick&dirty' solution:

Code: [Select]
$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
Der blaue Planet - er ist nicht unser Eigentum - wir haben ihn nur von unseren Nachkommen geliehen

"We need education to cope with digitalization - and NOT the digitalization of education.!"

Tägliches Stoßgebet: Oh Herr, wirf Hirn vom Himmel !

Offline crnogorac081

  • Posts: 2161
  • Gender: Male
Re: Searchbox with suggestions
« 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
Web developer

Offline DarkViper

  • Forum administrator
  • *****
  • Posts: 3087
  • Gender: Female
Re: Searchbox with suggestions
« 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
Der blaue Planet - er ist nicht unser Eigentum - wir haben ihn nur von unseren Nachkommen geliehen

"We need education to cope with digitalization - and NOT the digitalization of education.!"

Tägliches Stoßgebet: Oh Herr, wirf Hirn vom Himmel !

Offline crnogorac081

  • Posts: 2161
  • Gender: Male
Re: Searchbox with suggestions
« 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 :) 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
Web developer

doc

  • Guest
Re: Searchbox with suggestions
« 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

Offline crnogorac081

  • Posts: 2161
  • Gender: Male
Re: Searchbox with suggestions
« 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
Web developer

Offline DarkViper

  • Forum administrator
  • *****
  • Posts: 3087
  • Gender: Female
Re: Searchbox with suggestions
« Reply #13 on: February 02, 2010, 11:18:38 AM »
Quote from: crnogorac081 on February 02, 2010, 10:12:05 AM
'\';DELETE FROM `ul_pages`;';
into searchbox, and table is still there :) 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
Der blaue Planet - er ist nicht unser Eigentum - wir haben ihn nur von unseren Nachkommen geliehen

"We need education to cope with digitalization - and NOT the digitalization of education.!"

Tägliches Stoßgebet: Oh Herr, wirf Hirn vom Himmel !

Offline crnogorac081

  • Posts: 2161
  • Gender: Male
Re: Searchbox with suggestions
« 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
Web developer

Offline crnogorac081

  • Posts: 2161
  • Gender: Male
Re: Searchbox with suggestions
« Reply #15 on: February 03, 2010, 12:04:45 PM »
Also I tried this code to add slashes to DB call:

Code: [Select]
// 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
Web developer

Offline crnogorac081

  • Posts: 2161
  • Gender: Male
Re: Searchbox with suggestions
« Reply #16 on: February 04, 2010, 10:08:50 PM »
[[refresh]]  :-D
Logged
Web developer

finrodfelegund

  • Guest
Re: Searchbox with suggestions
« Reply #17 on: March 29, 2010, 11:58:06 PM »
i get this error , does anyone can help me. also if anyone can post the final look of the script with the security added!
Parse error: syntax error, unexpected T_STRING, expecting ',' or ';' in /home/coldhost/public_html/dorohoinews.ro/suggestion.php on line 30

thanks!!
Logged

Offline crnogorac081

  • Posts: 2161
  • Gender: Male
Re: Searchbox with suggestions
« Reply #18 on: March 30, 2010, 01:58:59 AM »
Hi,

I got no erors, it is working stable, see the demo. Are you sure the code is copied well?

cheers
Logged
Web developer

finrodfelegund

  • Guest
Re: Searchbox with suggestions
« Reply #19 on: March 30, 2010, 02:18:34 AM »
i got error here:
                        echo '<li onClick="fill(\''.addslashes($result['description']).'\');"><a href="'.WB_URL.PAGES_DIREC TORY.$result['link'].PAGE_EXTENSION.'">'.$result['page_title'].'</a></li>';

i think there is something wrong with the url:
href="'.WB_URL.PAGES_DIREC TORY.$result['link'].PAGE_EXTENSION.'"

donno whats that DIREC TROY

hmm

i removed DIREC TROY and i get a weird redirection to pages:
http://dorohoinews.ro/pages/reducere-a-impozitului.php
take a look

i am trying your jq script also :)

in the end i did a ugly hack of the code:
echo '<li onClick="fill(\''.addslashes($result['description']).'\');"><a href="'.WB_URL.'/pages'.$result['link'].PAGE_EXTENSION.'">'.$result['page_title'] .'</a></li>';

this seem to work for me - for the moment :) if someone could tell me whats wrong there i will be happy.
Now only problem is that the list its not going above the page :(
« Last Edit: March 30, 2010, 02:40:59 AM by finrodfelegund »
Logged

snark

  • Guest
Re: Searchbox with suggestions
« Reply #20 on: April 28, 2010, 10:51:44 PM »
when I put the code from the first post into a droplet I get a red droplet ...

Logged

Offline kweitzel

  • WebsiteBaker Org e.V.
  • **
  • Posts: 6983
  • Gender: Male
Re: Searchbox with suggestions
« Reply #21 on: April 29, 2010, 06:46:34 AM »
Quote
PAGES_DIREC TORY

looks like it should be:
Code: [Select]
PAGES_DIRECTORY
cheers

Klaus
Logged

Offline crnogorac081

  • Posts: 2161
  • Gender: Male
Re: Searchbox with suggestions
« Reply #22 on: April 29, 2010, 09:30:05 AM »
Hi Klaus,

I copy-pasted the code and because of code container width text was braked..

Thanks for letting other know if droplet error appears..

cheers
Logged
Web developer

Offline VSG

  • Posts: 276
Re: Searchbox with suggestions
« Reply #23 on: May 02, 2010, 05:37:13 PM »
As much as I like the concept of it and the demo on your site, I can't get it to work.
although I simply copied your code (and corrected the DIREC TORY mishap) it wouldn't show any suggestions.

The java-error-console gives the following report:
Code: [Select]
Uncaught exception: ReferenceError: Undefined variable: $
Error thrown at line 6, column 4 in lookup(inputString) in http://MYSITE/pages/forum2.php:
    $.post("http://MYSITE/suggestion.php", {queryString: ""+inputString+""}, function(data){   
called from line 1, column 0 in <anonymous function>(event):
    lookup(this.value);

MYSITE stands for my correct website-address.
Any ideas? I'd really like to make this work. By the way, does it work if all the pages are hidden? (Not private, just hidden.)

You can look for yourself here.
Thanks in advance!
Best regards,
VSG
Logged

Offline crnogorac081

  • Posts: 2161
  • Gender: Male
Re: Searchbox with suggestions
« Reply #24 on: May 02, 2010, 09:40:02 PM »
Hi mate,

there are no limitations regarding page visibility.

Regarding your issue (I forgot to mention, now I did in first post..), please add this line:

      <script type="text/javascript" src="<?php echo WB_URL; ?>/include/jquery/jquery-min.js"></script>

into your template's header.

all best,
Ivan
« Last Edit: May 02, 2010, 09:44:11 PM by crnogorac081 »
Logged
Web developer

  • Print
Pages: [1] 2   Go Up
  • WebsiteBaker Community Forum »
  • WebsiteBaker Support (2.8.x) »
  • Droplets & Snippets »
  • Searchbox with suggestions
 

  • SMF 2.0.19 | SMF © 2017, Simple Machines
  • XHTML
  • RSS
  • WAP2