The Concept of Security
Looking to better understand PHP security? Securing user input and output on pages is the key to keeping your site secure.
We don't like magic quotes in our user input
By user input, I refer to the $_GET and $_POST parameter variables. With the code below, we're going to check if magic quotes are on, and eventually simulate them being turned off.
<?php
if (get_magic_quotes_gpc()) {
//magic quotes are on, let's fix this
}
?>
Basically, if magic quotes are on, we're going to justify the situation. Magic quotes add backslashes before potentially dangerous characters in regards to security, but this goes against good practice when developing with PHP. A better point even, is that PHP6 will not have the magic quotes feature, so why not start developing like it's already gone?
Now that we have that explained, how do we handle user input? We register a callback function every $_GET and $_POST variable.
<?php
if (get_magic_quotes_gpc()) {
array_walk_recursive($_GET, 'input_cleanup');
array_walk_recursive($_POST, 'input_cleanup');
}
?>
array_walk_recursive() walks through each member of an array, and applies a callback function to it. Our function is called input_cleanup, and it looks like this:
<?php
if (get_magic_quotes_gpc()) {
array_walk_recursive($_GET, 'input_cleanup');
array_walk_recursive($_POST, 'input_cleanup');
}
function input_cleanup (&$value) {
$value = is_string($value) ? stripslashes($value) : $value;
}
?>
Notice the &$value in the function parameters, this represents an instance copy of the variable. Meaning, if we change the variable, it will also update the variable from wherever it came from. So what we do is check if the variable is a string, and if it is, we remove the slashes added by magic quotes. This simulates as if magic quotes were off, making your development environment easier and more practical.
Handling the new user input
Your user input will now never contain backslashes automatically added by magic quotes. By removing PHP's attempt at security, we need to add our own script specific security, as it should be. There are basically two rules to this;
- When handling user input in MySQL queries, use
mysql_real_escape_string()around your data to secure it 100%, allowing you to avoid any possibility of SQL injection. - When displaying user input on a page, or input that was entered into a MySQL database and displayed on a page, do not forgot
htmlspecialchars()! This prevents all XSS scripting possibilities, and also ensures that the output is W3C compliant, by encoding ampersands (&) to & and so on. NOTE: This includes populating forms from a MySQL database/
Furthering PHP security knowledge
I've showed you the essentials of user input and output security. But it is never wrong to keep building your knowledge of security. The most important thing in security is the cycle of events, what happens and when. Knowing how everything happens in a script or website makes it a lot easier to understand security.