A Web Developer's Diary

Pro-tip: when to avoid addslashes() in PHP

6/29/2012

2 Comments

 
When peer reviewing PHP code, I often find dangerous uses of addslashes(). It is often believed this is a safe way of escaping user input before passing it to e.g. a SQL query, but in fact it's unsafe. If you find yourself using addslashes(), think twice if you are using it safely:
  • In a MySQL context, use mysql_real_escape_string() instead.
  • MySQLi has an identical mysqli_real_escape_string().
  • PDO provides it's own escape method PDO::quote().
  • PostgreSQL has a wide variety of escape functions: pg_escape_literal() for values, pg_escape_bytea() for columns of type bytea, pg_escape_identifier() is used for escaping identifiers (e.g. table, field names).
  • When trying to pass user input to the command line, use escapeshellarg() and escapeshellcmd() to escape the input.
  • When displaying non-HTML user input anywhere on a webpage, always use htmlentities() or htmlspecialchars().
  • This one is a little awkward, but I've seen it before so I thought it's worth mentioning: when including user input in URLs, use urlencode() instead of addslashes()!

If you have more suggestions for safe escaping, please leave them in the comments below. Happy safe coding!
2 Comments
Erik
6/30/2012 12:38:54 pm

You see it often during peer review? That scares me -- it means not only are these clueless professionals, but if you see it often that means they continue to do it after you've corrected them (unless you change jobs a lot ... I guess )

Reply
webdevelopersdiary
6/30/2012 06:32:27 pm

Hi Erik,

As a freelancer, the people I work with change very frequently. It's not always professionals who make these mistakes, but yeah, I've seen it happen to professionals, too!

Reply

Your comment will be posted after it is approved.


Leave a Reply.

    Author

    Blog about random challenges of a web developer.

    Archives

    April 2015
    May 2013
    January 2013
    July 2012
    June 2012

    Categories

    All
    Aws
    Cdn
    Code Igniter
    Css
    H2database
    Jamp
    Java
    Javascript
    Magento
    Maven
    Mysql
    Opencl
    Php
    Play-framework
    Quercus
    Scala
    Ubuntu

    RSS Feed

Powered by Create your own unique website with customizable templates.