Automatically closing tags
Posted: Mon Jun 26, 2006 8:56 pm
Hello; I'm creating a guestbook-like system for my site, and so far I had no trouble creating code to prevent various injections. But there are is one problem that I don't know how to approach: unclosed tags. I know that phpBB does it with javascript; is there an efficient way of implementing this in server-side PHP? I'm allowing simple <b/i/u/s/code> tags only by converting them to phpBB-style square brackets tags.
Edit: the best I could come up with is
I don't know how well does this protect from HTML/CSS/JS evilness though.
Edit: the best I could come up with is
Code: Select all
$txt = trim($_POST["txt"]); // message text
$pat = array(); $rep = array();
$pat[0] = '/((http|https|ftp|mailto|steam):\/\/\S*?)(\s|$)/i'; // find URLs with protocols
$rep[0] = '[url]$1[/url]$3';
$pat[1] = '/(www\.\S*?)(\s|$)/i'; // find URL's starting with "www."
$rep[1] = '[url]http://$1[/url]$2';
//
$pat[2] = '/<(\/?[buis])>/i'; // allowed tags: <b>, <u>, <i>, <s>
$rep[2] = '[$1]';
$pat[3] = '/<(\/?code)>/i'; // allowed tag: <code>
$rep[3] = 'Code: Select all
';
$txt = strip_tags( preg_replace( $pat, $rep, $txt ) );
$tags = array( "url", "b", "u", "i", "s", "code" );
foreach( $tags as $tag ){
// if more tags of one kind are opened then closed,
// append the missing closing tags in the very end
while( substr_count( $txt, "[$tag]" ) > substr_count( $txt, "[/$tag]" ) ){
$txt.= "[/$tag]";
}
}
$txt = mysql_real_escape_string( htmlspecialchars( $txt ) ); // final precautions before sending off to SQL