Web Hosting Talk







View Full Version : PHP/MySQL and Search functionality - preventing hacking


Scott R
04-03-2003, 10:41 PM
I'm adding search functionality to my web site which will result in a $_GET variable which is a string/character variable and will end up in a MySQL SELECT query in a WHERE clause along the lines of:
WHERE ((title LIKE "%'.addslashes($_GET['search_text']).'%")

Is this open for hacking? IOW, can someone enter a destructive string in my search text box which could do some damage on my database? If so, what do I need to do to strip out any characters from this search? Or, does my use of the addslashes function take care of any/all hack issues here?

Thanks,

Scott

digitok
04-03-2003, 11:04 PM
Maybe you should remove the html tags too, it's up to you...

ilyash
04-04-2003, 01:00 PM
no damage can be done... but have a method which replaces certain characters... for example if they enter "%"
it will show everything in that table

also change " to '

if u want to disable html then replace < > with their ascii values..

Your Welcome,

zunilo
04-04-2003, 01:06 PM
It might also be worth taking a look at the mysql_escape_string function.

Scott R
04-04-2003, 03:04 PM
I ended up changing my code to the following:

$sSlashedSearchFilter = str_replace('_', '\_', str_replace('%', '\%', mysql_escape_string($sSearchFilter)));

$sSQL = ' SELECT * FROM table WHERE page_body LIKE "%'.$sSlashedSearchFilter.'%"';

This seems to work pretty well but isn't perfect for my needs. I discovered in my testing that I had some content where I had some freaky characters in my page_body field in the DB. For instance, the character “ which is different from the normal double quote " found on a keyboard. You'll notice that the former is tilted. Well, that's stored in my DB but if I do a search on it, it doesn't bring back that row. Still, that's a bit of an oddity, so I'm not too worried.

More troublesome is that because this is a home-grown content management system, I have some text in my page_body fields with certain allowable HTML characters (such as the one for bold text). So, if I have the text "Hello <b>Joe</b>" in my database and a user does a search for "Hello <b>Joe</b>" they'll get the row back but if they do a search for "Hello Joe" they won't. I don't see any way around this problem, though, since it would require an MySQL function which would permit something like:
$sSQL = ' SELECT * FROM table WHERE strip_html(page_body) LIKE "%'.$sSlashedSearchFilter.'%"';

Scott

LinuXpert
04-04-2003, 08:57 PM
http://www.google.com/search?sourceid=navclient&ie=UTF-8&oe=UTF-8&q=how+to+prevent+SQL+injection

Eric