Search code examples
phphtml-entitiesmysql-real-escape-stringstrip-tags

html_entities Vs strip_tags with mysql_real_escape_string


I have a question upon Strip_tags, html_entities and mysql_real_escape_string.

Now when I use for example:

strip_tags(mysql_real_escape_string($_POST['username']));

This code above will be safe as well as this:

html_entities($_POST['username']);

Which one is more safer for a real world project.

And what is the the benefit for using strip_tags and mysql_real_escape_string together. But when I use html_entities with them it won't work


Solution

  • You have to clear purpose at first. There's no all-around escapeing.

    htmlspecialchars or htmlentities

    Purpose

    Display user inputs as HTML.

    Example

    <div><?php echo htmlspecialchars($_POST['data'], ENT_QUOTES, 'UTF-8') ?></div>
    

    Note

    Use this function when you just about to display it. Do not apply it to store into variables beforehand.

    Has this variable been already escaped...?

    ... You may trouble yourself.

    strip_tags

    Do not use this function. SANITIZE is a wrong way.

    mysql_real_escape_string

    Purpose

    Set user inputs in SQL.

    Example

    <?php
    $sql = sprintf(
        "SELECT * FROM table WHERE name = '%s' AND address = '%s'",
        mysql_real_escape_string($_POST['name'], $link),
        mysql_real_escape_string($_POST['address'], $link)
    );
    

    Note

    mysql_* functions are all deprecated. You'd better use PDO. PDO provides us Prepared Statements and Placeholders, instead of escaping.

    PHP Manual - PDO::prepare