Ti basta utilizzare htmlentities() prima di memorizzare la variabile in database
Codice PHP:
$testo = htmlentities($_POST['testo']);
mysql_query("INSERT INTO tabella (testo) VALUES ('$testo')");
questo per quanto riguarda l'SQL injection.
Quando devi stampare il testo, dovrai riconvertire le entità in codice html:
Codice PHP:
$row = mysql_fetch_assoc(mysql_query("SELECT testo FROM tabella"));
$testo = html_entity_decode($row['testo']);
A questo punto però sei vulnerabile agli attacchi XSS.
Per fare ciò devi eliminare tag come <script> e <iframe>
Codice PHP:
function strip_selected_tags($text, $tags = array()) {
$args = func_get_args();
$text = array_shift($args);
$tags = func_num_args() > 2 ? array_diff($args,array($text)) : (array)$tags;
foreach ($tags as $tag){
if(preg_match_all('/<'.$tag.'[^>]*>([^<]*)<\/'.$tag.'>/iu',$text,$found) ){
$text = str_replace($found[0],$found[1],$text);
}
}
return @$text;
}
$strip = array('iframe','script');
$testo = strip_selected_tags($testo,$strip);
Questo è un modo, ma ve ne sono molti altri