Im building a public forum from scratch, and im fine tuning, and testing everything now. Im currently stuck at the function that strips all html tags expect those i use for insering youtube-videoes, and bold/italic tags so that the user atleast has some way of styling their posts. My problem, is that when i use the nl2br2() function for filtering my post-string, it dosnt strip the html-tags from the string, it works fine if i remove nl2br2() ..? My theory is that the strip_tags() function also strips the native system line breaks \n and \r, so that nl2br2() haven't got any line break to convert. Im actually pretty sure, that's the problem! How can i make those two functions work together? Is there any alternatives to strip_tags()? Or can you somehow tell the function, to stop stripping those linebreaks!!? Its really annoying, been spending lots of hours today trying to figure this out :D any help is much apreaciated!
THIS DIDN'T WORKD:
function nl2br2($string) {
$string = str_replace(array("\r\n", "\r", "\n"), "<br />", $string);
return $string;
}
$str = "$_POST[indlaeg]";
mysql_real_escape_string($str); // PROTECT FROM SQL INJECTIONS THROUGH SINGLE QUOTES ''
strip_tags($str, '<b><i><a><video><br>'); // REMOVE ALL TAGS EXPECT
$str = nl2br2($str); // CONVERT LINE BREAKS TO <br>
THIS DIDN'T WORK EITHER:
$str = mysql_real_escape_string(strip_tags(nl2br2($_POST['indlaeg']), '<b><i><a><video><br>'));
THIS WORKED!!!!
function html2txt($document){
$search = array('@<script[^>]*?>.*?</script>@si', // Strip out javascript
'@<[\/\!]*?[^<>]*?>@si', // Strip out HTML tags
'@<style[^>]*?>.*?</style>@siU', // Strip style tags properly
'@<![\s\S]*?--[ \t\n\r]*>@' // Strip multi-line comments including CDATA );
$text = preg_replace($search, '', $document);
return $text;
}
$str = "$_POST[indlaeg]";
$str = html2txt($str);
$str = nl2br2($str);
The html2txt() function is sent from heaven! It strips ALL evil-minded tags! Including the single quotes '' that hackers like to use for SQL injection :D
PROBLEM SOLVED!
You’re applying three functions to your string –
mysql_real_escape_string
,strip_tags
andnl2br2
. The order should be reversed becausemysql_real_escape_string
adds a backslash before\n
and\r
, making the string unable to be processed bynl2br2
. If you applynl2br2
first,strip_tags
next andmysql_real_escape_string
last, no such problems should arise.Replace these four lines
with