Search code examples
phpmysqlmysql-real-escape-stringstripslashes

Do I really need to use mysql_real_escape_string when I save data in the DB?


I am using mysql_real_escape_string to save content in my mySQL database. The content I save is HTML through a form. I delete and re-upload the PHP file that writes in DB when I need it.

To display correctly my HTML input I use stripslashes()

In other case, when I insert it without mysql_real_escape_string, I do not use stripslashes() on the output.

What is your opinion? Does stripslashes affect performance badly ?


Solution

  • Do not use stripslashes(). It is utterly useless in terms of security, and there's no added benefit. This practice came from the dark ages of "magic quotes", a thing of the past that has been eliminated in the next PHP version.

    Instead, only filter input:

    • string: mysql_real_escape_string($data)
    • integers: (int)$data
    • floats: (float)$data
    • boolean: isset($data) && $data

    The output is a different matter. If you are storing HTML, you need to filter HTML against javascript.

    Edit: If you have to do stripslashes() for the output to look correctly, than most probably you have magic quotes turned on. Some CMS even made the grave mistake to do their own magic quotes (eg: Wordpress). Always filter as I advised above, turn off magic quotes, and you should be fine.