0

I am using jQuery to serialize a form and then POST it via ajax to the back-end to be saved to MySQL.

I've run into a problem where, for text fields containing quotation marks " and ', jQuery's .serialize() adds an escaping slash, which gets POSTed.

For Example: ' Monitor Size: 22" ' is being saved as ' Monitor Size: 22\" '. These slashes also accumulate as the field is further edited and re-saved, so that it eventually might look like 'Monitor Size: 22\\\\\\" '.

I could remove all back-slashes when processing the $_POST in PHP, but that would also remove any back-slashes that the user might have legitimately entered.

Is there another way to avoid this somehow?

Ideas Much Appreciated!

Niko Efimov
  • 2,183
  • 3
  • 20
  • 30
  • 2
    Other than fix your PHP settings to not add them in the first place? – Ignacio Vazquez-Abrams Dec 16 '10 at 21:50
  • Yikes. So *this* is how so many sites get simultaneously broken by reproducing slashes/escapes, and *also* still remain vulnerable to all sorts of SQL injection hijinks... I just hope you know why those slashes are being added, and know what to do with the resulting strings once they are removed, before feeding them to your SQL – Andrew Barber Dec 16 '10 at 21:50
  • 1
    jQuery **does not do this** -- `>>> $("
    ").serialize();` -- result: `"test=%22test%22"`
    – gnarf Dec 16 '10 at 21:58
  • DB management is handled by Zend Framework, where, as far as I could tell, the DB inputs are automatically sanitized. I hope so? – Niko Efimov Dec 16 '10 at 22:09
  • E. - Yes - ZF will use the correct escaping method for database sanitation – gnarf Dec 16 '10 at 22:20

3 Answers3

4

I would bet that it's not jQuery doing it, but the PHP server you're using has magic quotes enabled.

So either disable magic quotes, or strip the slashes yourself before saving to the DB

Peter Bailey
  • 105,256
  • 31
  • 182
  • 206
  • Rather - Don't double escape your slashes while adding to db... Stripping them entirely is like painting a bullseye on your chest. – gnarf Dec 16 '10 at 21:56
  • @gnarf: you should use the relevant DB escaping function, e.g. `mysql_real_escape_string` when writing queries. – Andy E Dec 16 '10 at 21:58
  • @Andy E - Right- hence not passing an already escaped version therefore 'double escaping' (boo magic quotes) -- Also for reference [SO: How can I disable PHP magic quotes at runtime?](http://stackoverflow.com/questions/1153741) – gnarf Dec 16 '10 at 22:00
  • Both stripslashes and disabling magic quotes solved the issue. I have chosen to just disable magic quotes. Thanks! – Niko Efimov Dec 16 '10 at 22:06
2

Please check stripslashes() function of PHP...

Kishan Gajjar
  • 1,120
  • 3
  • 22
  • 43
1

I assume that if user puts in a 'legitimate' backslash it gets escaped as well, so stripslashes() should do it's job.

Mchl
  • 61,444
  • 9
  • 118
  • 120