How to be safe from XSS attacks, but allow

First, an example of my database table:

+----+-----------+-------------------------------------+
| id | user_id   | text                                |
+----+-----------+-------------------------------------+
| 12 | 45        | Hi, <br>this is an example. <br>Bye |
+----+-----------+-------------------------------------+

      

I always use prepared MySQLi statements, so SQL injection is no longer a problem, is it?

Now the problem with XSS attacks:

I want to safely output text from a database table, so the general method would be htmlentities

with the ENT_QUOTES

following:

htmlentities($ValueFromDatabase, ENT_QUOTES, 'UTF-8');  

      

But I don't want to hide the tags <br>

that are in the database.

How to avoid all dangerous things, but <br>

? Or is there another method for breaking displaying lines (with a database)?

EDIT: Possible solution?

//------INSERTING------
if (isset($userinput) AND $userinput != "") {
    $userinput = $_POST['userinput'];
} else {
    //Error Handling
    exit;
}

$userinput2 = nl2br($userinput);
$userinput3 = str_replace("<br />","[br]",$userinput2);

$sql = $mysqli->prepare('INSERT INTO table (col1) VALUES (?)');
$sql->bind_param('s', $userinput3);
$sql->execute();

//------DISPLAYING------
$sql = $mysqli->prepare('SELECT userinput FROM table WHERE userid = ?');
$sql->bind_param('i', $userid);
$sql->execute();
$sql->store_result();
$sql->bind_result($userinput);
$sql_rows = $sql->num_rows;

if ($sql_rows != 0) {
    while ($sql->fetch()) {
        echo str_replace("[br]","<br />",htmlentities($userinput, ENT_QUOTES, "UTF-8"));
    }
} else {
    echo'No rows in the database.';
}

      

+3


source to share


1 answer


You should really try http://htmlpurifier.org/ It's a good XSS prevention library, and it still allows some tags like <br> , <b>, <i> and other safe tags.



0


source







All Articles