Below is a simple PHP function that I use to strip any dangerous code from my input boxes.


<?php

// make our user input safe to output

function safe_output($string){

$string = trim($string);

$string = strip_tags($string);

$string = htmlspecialchars($string);

return $string;

}

// retrieve form data

$phrase = safe_output($_POST['phrase']);

?>

First we are going to create a function called “safe_output”, and within that function we are going to perform a set of statements that will trim and strip any whitespace and code from our textbox and give us just the raw string.

Within our function we are going to create the variable $string.  Then we are going to pass $string through the “trim” function which will remove any whitespace before and after our string (Example: “Bill Gates     “ becomes “Bill Gates”).

Next we will pass our variable through the “strip_tags” function which will strip out any HTML and PHP tags from our string (Example: “<html><body>Bill Gates</body></html>” becomes “Bill Gates”).

Then finally we will pass our variable through the “htmlspecialchars” function which will convert any special characters to HTML entities (Example: “&” will become “&amp”, and “>” will become “&gt”, etc…).

Lastly we create a new variable called “$phrase” that passes the string from our form through our safe_output function.