Re: Sanitizing mysql inserts of user data

From: Date: Sun, 16 Aug 2009 19:31:27 +0000
Subject: Re: Sanitizing mysql inserts of user data
References: 1 2  Groups: php.general 
Request: Send a blank email to php-general+get-296855@lists.php.net to get a copy of this message
2009/8/16 Caner Bulut <canerblt@gmail.com>: > > Hi Dotan, > > You can use htmlentities(), htmlspecialchars() and strip_tags() functions > when you show your saved data on your web pages. mysql_real_escape_string > function saved data into mysql DB with a secure way. But when you try to > show data you still have to control it. > Thank you Caner. This is the function that I use to escape HTML after it has been pulled out of the database: function clean_html ($dirty, $noNewlines=0) { $dirty = strip_tags($dirty); $dirty = str_replace("\r\n", "\n", $dirty); $dirty = str_replace("\r", "\n", $dirty); if ($noNewlines==1) { $dirty = str_replace("\n", " ", $dirty); } $dirty = ereg_replace( ' +', ' ', $dirty); $dirty=trim($dirty); $dirty = str_replace("&amp;", "&", $dirty); $dirty = str_replace("&", "&amp;", $dirty); $clean=htmlentities($dirty); return $clean; } It is rather convoluted but straightforward in my opinion. In addition to preventing XSS attacks, it converts newlines to *nix-style and limits them to just two newlines in a row (or none, depending on application). It also limits spaces to a single space and ensures that all ampersands are escaped properly before sanitation with htmlentities. Dotan Cohen

« previous php.general (#296855) next »