addslashes() [PHP]


SUBMITTED BY: Guest

DATE: May 7, 2014, 6:44 p.m.

FORMAT: PHP

SIZE: 1.0 kB

HITS: 1464

  1. Beware of using addslashes() on input to the serialize() function. serialize() stores strings with their length; the length must match the stored string or unserialize() will fail.
  2. Such a mismatch can occur if you serialize the result of addslashes() and store it in a database; some databases (definitely including PostgreSQL) automagically strip backslashes from "special" chars in SELECT results, causing the returned string to be shorter than it was when it was serialized.
  3. In other words, do this...
  4. <?php
  5. $string="O'Reilly";
  6. $ser=serialize($string); # safe -- won't count the slash
  7. $result=addslashes($ser);
  8. ?>
  9. ...and not this...
  10. <?php
  11. $string="O'Reilly";
  12. $add=addslashes($string); # RISKY! -- will count the slash
  13. $result=serialize($add);
  14. ?>
  15. In both cases, a backslash will be added after the apostrophe in "O'Reilly"; only in the second case will the backslash be included in the string length as recorded by serialize().

comments powered by Disqus