开发者

Insert HTML content into db table securely

开发者 https://www.devze.com 2023-04-10 14:46 出处:网络
I\'m using HTML fu开发者_JAVA技巧nction for inserting html content into db table and filter for filtering user inputs against SQL injection attacks. getting output like this prntscr.com/3c8ht .I got f

I'm using HTML fu开发者_JAVA技巧nction for inserting html content into db table and filter for filtering user inputs against SQL injection attacks. getting output like this prntscr.com/3c8ht . I got following questions:

1) From which functions HTML content needs to be passed before insert and while output? 2) What else for filter function needed or is there any unused function?

Thx in advance

function filter($data, $db)
{
    $data = $db->escape_string($data);
    $data = htmlspecialchars($data, ENT_IGNORE, 'utf-8');
    $data = strip_tags($data);
    $data = stripslashes($data);
    $data = htmlentities($data);
   return $data;
}

function html($data, $db)
{     
    $data = $db->escape_string($data);
    return $data;
}


You should use the escaping tool required by the medium, not just anyone anywhere.

To avoid SQL injection, mysql_real_escape_string() is, at minimun, what you need to use. A better alternative is using prepared statements and paramerized queries (look into PDO extension, which is shipped with PHP since v 5.1 IIRC), which will be the safest option to avoid this kind of exploit.

Sending unescaped html to the db does nothing, since malicious scripts aren't of course executed. HMTL needs to be sanitized ON OUTPUT, whenever you're going to print it out on the page, and should be done only when needed, not a priori.

To secure html you can use htmlentities(), as minimum step. You might also want to consider complex filters to replace occurrencies of "bad" words and bad characters: this is a more complex case which requires a long set of operations but of course will grant you the most accurate level of security. You can ask another question for this topic, or search here on SO.
Strip_tags() might just break your markup (it won't be html anymore, more likely plain text), besides not being in itself secure at all.


Every time you use user's input to store in database, you should use mysql_real_escape_string().

Now if you retrieving some long text which contains newline feeds, use nl2br() while printing the data.

http://php.net/manual/en/function.mysql-real-escape-string.php

0

精彩评论

暂无评论...
验证码 换一张
取 消