0

I have been trying to sanitize user input for saving safely in the database and then redisplaying.

If a user enters something like M'Cain for the name, how should I sanitize it before sending to the database, and then when reading back, deal with it so that it displays correctly.

Currently I am using sanitize_text_field which adds the \ before the apostrophe, but this then displays when I display it back.

Do I simply use strip_slashes before outputing back to the screen or another function?

Álvaro González
  • 142,137
  • 41
  • 261
  • 360
StripyTiger
  • 877
  • 1
  • 14
  • 31
  • 1
    Are you using `mysqli` or `PDO`? If yes, use `prepared statements` – Professor Abronsius Jul 12 '19 at 14:58
  • If neither of these two options, then you should use prepared statements. Check the API you use for prepared statements. – Dharman Jul 12 '19 at 15:03
  • I'm using Wordpress - using $wpdb->prepare to bind the parameters. – StripyTiger Jul 12 '19 at 15:07
  • 2
    Then you should not be sanitizing the data. If you do you are risking SQL injection. Wordpress does not use prepared statements unfortunately, because it is many years old. However they emulate it with `$wpdb->prepare` which is what you use. – Dharman Jul 12 '19 at 15:10
  • OK - thanks - but what about stopping javascript being entered in the input fields - and then displaying this back on a screen. – StripyTiger Jul 12 '19 at 15:12
  • Would using strip_tags stop this? – StripyTiger Jul 12 '19 at 15:20
  • @StripyTiger Use `htmlentities()` when displaying data on a web page. It will display all the HTML tags literally, instead of interpreting them as HTML markup. – Barmar Jul 12 '19 at 15:44
  • I suggest you stop thinking of data as something that's either dangerous or sanitized because that's not how it work and all the solution you propose will basically corrupt user input. Data is dangerous when *you* handle it in such a way that it runs as code. I've also added the [tag:wordpress] tag because it's totally relevant to the question. – Álvaro González Jul 12 '19 at 16:04
  • use `esc_html( $string );` while echoing. – Sahriar Saikat Jul 12 '19 at 18:00
  • Also you can prevent Javascript and other html inputs by using [wp_strip_all_tags()](https://developer.wordpress.org/reference/functions/wp_strip_all_tags/) – Sahriar Saikat Jul 12 '19 at 18:02
  • OK - thank you all for your help. So writing to the database, just carry on using wpdb->prepare, When displaying the data back to the screen, then use htmlentities. The original apostrophe in M'Cain is being sent from a javascript object in an ajax call, so the \ is being inserted here. If I just use strip_slashes in php before inserting, is that acceptable? – StripyTiger Jul 15 '19 at 09:35

0 Answers0