This is a continuation of the PHP coding articles I have been writing. This article covers a very important basic in PHP development, escaping data. Everywhere there is a heavy PHP development that requires inserting information into a Database, if it is scripted correctly you will see that this information/data is more than likely escaped. Escaping data is very important to maintaining the integrity of what goes into a database.
Golden Rule: Any data that is not filtered or escaped and is sent via means of someone else on your website is considered tainted. Let’s take a form submission for example. Jack Johnson fills out a contact form with his name, email, description and subject and pressed SEND. All of this text is considered tainted until escaped/filtered. Hackers just love to use contact forms for SQL injections and is an age old trick to gain access to areas of your server.
How to escape
To illustrate the importance of escaping everything, let’s look at a pattern where escaping is commonly omitted: Form elements.
A form may look like this:
<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label> <input type="text" id="<?php echo $this->get_field_id( 'title' ); ?>" title="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" value="<?php echo esc_attr( $title ); ?>"/>
Let’s see what happens when we drop this bit of code anywhere in our code base:
$form->id_base = '"><script>alert("Greetings! You have been hacked.");</script>"<';
$this->db->query("INSERT INTO " . DB_PREFIX . "banner SET name = '" . $this->db->escape($data['name']) . "', status = '" . (int)$data['status'] . "'");
Here you can see the function
This function you can wrap around any data that is going into the DB upon an INSERT QUERY. It allows you to have the peace of mind knowing that the data is no longer tainted and your server is in general safer than it was prior to the action.
To get more knowledge on a php function that directly deals with this please visit: http://php.net/manual/en/function.mysqli-escape-string.php.
Escape the following characters with HTML entity encoding to prevent switching into any execution context, such as script, style, or event handlers. Using hex entities is recommended in the spec. In addition to the 5 characters significant in XML (&, <, >, “, ‘), the forward slash is included as it helps to end an HTML entity.
& --> & < --> < > --> > " --> " ' --> ' ' not recommended because its not in the HTML spec ' is in the XML and XHTML specs. / --> / forward slash is included as it helps end an HTML entity