Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP Building Websites with PHP Slim Basics & Twig Templates Installing Twig

Mayur Pande
Mayur Pande
Courses Plus Student 11,711 Points

Escaping special characters

Hi I am a little confused about escaping special characters. Hampton says that it is useful to escape special characters as we never want to trust user data. Why is this?

1 Answer

One such reason to escape characters is because they can be used to do malicious things. An important example is when you are working with MySQL connections, using mysql_real_escape_string() to escape any characters which could be used to inject data into a database http://php.net/manual/en/function.mysql-real-escape-string.php.

// Connect
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')
    OR die(mysql_error());

// Query
$query = sprintf("SELECT * FROM users WHERE user='%s' AND password='%s'",

In the above example, if you did not escape user name or password someone could modify the query to select any user, or even drop the database table.

Mayur Pande
Mayur Pande
Courses Plus Student 11,711 Points

Thank you for the answer, there is one thing I am still slightly confused with. You say in the example above that the query could be modified by someone. How could the query be accessed?

So typically the variables are query would be using are pulled from a POST from a form. So when you see a username and password login form, what you type in is being posted to a PHP script on the server. Depending on the query you could do something like x'; DROP TABLE users; -- in one of the fields and it would drop the table (assuming the DB wasn't read only).

The reason this works is because a query is really just a string of commands and because of how quotes and comments are used within the string, you can modify or append to the query with just about anything. That is why you need to escape certain characters and only allow very specific data within these fields.

Heres a nice article on the subject of SQL injections: http://www.unixwiz.net/techtips/sql-injection.html