Field Protection

Posted by Pete | Posted in PHP Functions | Posted on 16-07-2009-05-2008

3

Injection into websites is getting more and more common, This is due to more hackers/kids learning to deface peoples websites for the “Fun of it”. But one main way to stop them is protecting your forms. Below is a function which removes all tags e.g HTML, PHP etc and turns all htmlentities such as ” ‘ & etc into the html forms.

<?php
// Field Protection Function
function protection($field) // Start Of Function.
{
    if (empty($field)) // Checks if $field is empty.
    {
        $return[error] = "Value Empty"; // If $field is found to be empty it will return an error message.
    }
    else
    {
        if (is_array($field)) // Checks if $field is an array or not.
        { // If it is an array then carry on.
			foreach($field as $key => $value){ // Carry out the foreach on the $field assigning the key and value of the array to $key and $value.
				$key = strip_tags($key); // Remove any tags from the field
				$value = strip_tags($value); // Remove any tags from the field
            	$field[$key] = htmlentities($value, ENT_QUOTES); // Convert all applicable characters to HTML entities
			}
			$return = $field; // Assign $field array to $return.
		}
        else // If $field isnt an array carry out the following.
        {
            $field = strip_tags($field); // Remove any tags from the field.
            $return = htmlentities($field, ENT_QUOTES); // Convert all applicable characters to HTML entities.
        }
    }
    return $return; // Return $return
}
?>

I have commented all lines so if you read them you should be able to understand whats happening. Now youve got the function you need to be able to use it. To call a function you simply type its name e.g protection($_POST);

<?php
if(isset($_POST[submit){
$_POST = protection($_POST);
// Rest of form submittion stuff here
}else{
//Form Goes Here
}
?>

As you can see its simple to implement and protects from most simple things. If you need any help with it just leave a comment and i’ll get back to you.

Comments posted (3)

What does “ENT_QUOTES” do?

There are 3 constants which can be used with the function htmlentities.

Constant Name Description
ENT_COMPAT – Will convert double-quotes and leave single-quotes alone.
ENT_QUOTES – Will convert both double and single quotes.
ENT_NOQUOTES – Will leave both double and single quotes unconverted.

[...] tutorial is an advancement to the first tutorial (here). This tutorial is able to run every time the page loads and removes any tags and helps stop [...]

Write a comment

You must be logged in to post a comment.

Tutorials Written By Peter Kelly