5

What do people use stripslashes for and is it typically used in conjunction with addslashes? Why should I strip or add slashes to a string that's submitted by a user?

locoboy
  • 38,002
  • 70
  • 184
  • 260

1 Answers1

6

You should always sanitize the user's input. But not with addslashes()... If you want to compose a query with the user's input, use the proper database escaping mechanism (look into mysql_real_escape_string() and PDO prepared statements).

The reason for sanitizing user input is security. Read about SQL injection and cross-site scripting, which are the two most common security problems arising from un-sanitized input.

rid
  • 61,078
  • 31
  • 152
  • 193
  • 1
    So what is the proper way to sanitize statements with stripslashes and why do I need to strip the slashes? – locoboy Jun 19 '11 at 01:10
  • `stripslashes()` does not sanitize statements... you don't need to use `stripslashes()` unless you have a string containing `\'` sequences and you want to remove the backslashes. – rid Jun 19 '11 at 01:13
  • I see. So when inserting something into the database I sanitize with mysql_real_escape_string then when I retrieve and display I use stripslashes? – locoboy Jun 19 '11 at 01:20
  • 1
    `mysql_real_escape_string()` ensures that the string is properly passed to the query, thus not getting any extra slashes. You don't need to use `stripslashes()` when getting the string back. Do however use [`htmlspecialhars()`](http://php.net/htmlspecialchars) when displaying *any* text to the user that you don't compose yourself (such as those obtained from the database or from other users). – rid Jun 19 '11 at 01:23
  • 1
    @Cfarm: no. the slashes will NOT be stored in the database. That's the whole point of escape characters. As soon as they pass through something that understands them, one level of escaping is removed. – Marc B Jun 19 '11 at 01:54