Welcome, Guest. Please login or register.
Did you miss your activation email?
February 13, 2012, 01:04:56 AM

Login with username, password and session length
Search:     Advanced search
Interested in joining the WebsiteBaker team?
For more Information read here or on our new website.
149699 Posts in 21103 Topics by 7538 Members
Latest Member: ionline
* Home Help Search Login Register
Pages: [1] 2   Go Down
Print
Author Topic: Searchbox with suggestions  (Read 4664 times)
crnogorac081
AddOn Development
*
Offline Offline

Posts: 1680



« 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 Smiley
« Last Edit: May 02, 2010, 08:47:58 PM by crnogorac081 » Logged

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

Posts: 2814



WWW
« 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

Offline Offline

Posts: 81


« 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
AddOn Development
*
Offline Offline

Posts: 1680



« 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
Development Team
*****
Offline Offline

Posts: 1052


« 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, 01:01:32 AM by DarkViper » Logged

Anleitungen lesen und selber nachdenken ist anstrengend...  Da lass ich doch lieber andere für mich denken...

In 1984:  Nineteen Eighty-Four is a unrealistic utopia!!
In 2012:  Nineteen Eighty-Four is a little piece only of our reality!!
crnogorac081
AddOn Development
*
Offline Offline

Posts: 1680



« 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
AddOn Development
*
Offline Offline

Posts: 1680



« 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
Development Team
*****
Offline Offline

Posts: 1052


« 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

Anleitungen lesen und selber nachdenken ist anstrengend...  Da lass ich doch lieber andere für mich denken...

In 1984:  Nineteen Eighty-Four is a unrealistic utopia!!
In 2012:  Nineteen Eighty-Four is a little piece only of our reality!!
crnogorac081
AddOn Development
*
Offline Offline

Posts: 1680



« 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
Development Team
*****
Offline Offline

Posts: 1052


« 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

Anleitungen lesen und selber nachdenken ist anstrengend...  Da lass ich doch lieber andere für mich denken...

In 1984:  Nineteen Eighty-Four is a unrealistic utopia!!
In 2012:  Nineteen Eighty-Four is a little piece only of our reality!!
crnogorac081
AddOn Development
*
Offline Offline

Posts: 1680



« 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
Guest
« 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
AddOn Development
*
Offline Offline

Posts: 1680



« 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
Development Team
*****
Offline Offline

Posts: 1052


« 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

Anleitungen lesen und selber nachdenken ist anstrengend...  Da lass ich doch lieber andere für mich denken...

In 1984:  Nineteen Eighty-Four is a unrealistic utopia!!
In 2012:  Nineteen Eighty-Four is a little piece only of our reality!!
crnogorac081
AddOn Development
*
Offline Offline

Posts: 1680



« 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
AddOn Development
*
Offline Offline

Posts: 1680



« 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
AddOn Development
*
Offline Offline

Posts: 1680



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

[[refresh]]  grin
Logged

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

Offline Offline

Posts: 6


« Reply #17 on: March 29, 2010, 10: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
crnogorac081
AddOn Development
*
Offline Offline

Posts: 1680



« Reply #18 on: March 30, 2010, 12: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

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

Offline Offline

Posts: 6


« Reply #19 on: March 30, 2010, 01: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 Smiley

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 Smiley 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 Sad
« Last Edit: March 30, 2010, 01:40:59 AM by finrodfelegund » Logged
snark
Guest
« Reply #20 on: April 28, 2010, 09:51:44 PM »

when I put the code from the first post into a droplet I get a red droplet ...

Logged
kweitzel
Forum administrator
*****
Offline Offline

Posts: 6823


WWW
« Reply #21 on: April 29, 2010, 05:46:34 AM »

Quote
PAGES_DIREC TORY

looks like it should be:
Code:
PAGES_DIRECTORY

cheers

Klaus
Logged

WebsiteBaker Org e.V. - for WebsiteBaker

crnogorac081
AddOn Development
*
Offline Offline

Posts: 1680



« Reply #22 on: April 29, 2010, 08: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

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

Offline Offline

Posts: 100


« Reply #23 on: May 02, 2010, 04: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:
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
crnogorac081
AddOn Development
*
Offline Offline

Posts: 1680



« Reply #24 on: May 02, 2010, 08: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, 08:44:11 PM by crnogorac081 » Logged

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

Powered by MySQL Powered by PHP Powered by SMF 1.1.16 | SMF © 2011, Simple Machines Valid XHTML 1.0! Valid CSS!