PHP COTW: htmlspecialchars, intval and str_replace

The second PHP code of the week are htmlspecialchars, intval and str_replace which can all be used to process user form input before you use that input in your code.

htmlspecialchars basically converts the HTML characters like single and double quotes, less than, more than and ampersand signs to entities; which means that using this function we can prevent the users text from containing HTML characters.

echo htmlspecialchars(“<a href=’test’>Test</a>”);

This example will output in the browsers source code:
[php]<a href=’test’>Test</a>[/php]

intval is a way we can convert anything to an integer since we are expecting an integer. This means we can covert a string containing a number to a integer. We can be sure that we will only receive a number and nothing else.

[php]echo intval(‘035’);[/php]

The example will output 35. If the string contains any other characters other than digits it will return 0 (unless the digits are at the start of the string).

A full example of htmlspecialchars and intval would be:

[php]$sort_order = htmlspecialchars($HTTP_POST_VARS[‘order’]);
$form_status = intval($HTTP_POST_VARS[‘status’]);[/php]

str_replace is used to protect us from SQL injections into our database. If you aren’t protected from SQL injections, this means a user could perform any SQL query that you have access to.

For example, you could be updating a users email address in your database and the user types into the email address field.

[php]’; DROP some_table; some_fake_query_here(‘[/php]

The original query is below.

[php]UPDATE userdata SET email_address = ‘$form_email’ WHERE user_id = ‘$user_id’;[/php]

So what is going on you say? Below is what the resulting SQL statement looks like after the form has been processed.

[php]UPDATE userdata SET email_address = ”; DROP some_table; some_fake_query_here(” WHERE user_id = ‘5234’;[/php]

So what happens is the first query is processed we try not to break this query or all other queries would then fail. The second query to drop the table is successful and the table is therefore dropped and the last query fails.

So if we want to protect ourselfs from an SQL injection we use this code below.

[php]str_replace(“\'”, “””, $variable_name);[/php]

If form fields that a user submits contain a quote they are automatically re-written as \’. What our code will do is make it database friendly. It converts \’ to ” which for the database means it will be represented as a single quote. We have therefore solved the SQL injection issue.

On the next PHP code of the week we will cover isset and empty which are other functions which should be considered when processing forms.

Leave a Reply