php sanitize post data code example
Example 1: sanitize form data php
function clean($data)
{
$data = htmlspecialchars($data);
$data = stripslashes($data);
$data = trim($data);
return $data;
}
Example 2: php filters
#Filter Validation
<?php
if(filter_has_var(INPUT_POST,'data')){
$email = $_POST['data'];
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
echo $email.'<br>';
if(filter_input(INPUT_POST, 'data', FILTER_VALIDATE_EMAIL)){
echo 'Email is Valid';
}else{
echo 'Email is not Valid';
}
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
echo 'Email is Valid';
}else{
echo 'Email is not Valid';
}
}
$var = 'john';
if(filter_var($var, FILTER_VALIDATE_INT)){
echo '<br>'.$var.' is a number<br>';
}else{
echo '<br>'.$var.' is not a number'.'<br>';
}
$var2 = '33k2dsdffgsdf3563sdf';
var_dump(filter_var($var2, FILTER_SANITIZE_NUMBER_INT));
$filters = array(
"data" => FILTER_VALIDATE_EMAIL,
"data2" => array(
"filter" => FILTER_VALIDATE_INT,
"options" => array(
"min_range" => 1,
"max_range" => 100
)
)
);
print_r(filter_input_array(INPUT_POST, $filters));
?>
<form method ="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<input type="text" name="data">
<input type="text" name="data2">
<button type="submit">Submit</button>
</form>
Example 3: php sanitize $POST
$_GET = filter_input_array(INPUT_GET, FILTER_SANITIZE_STRING);
$_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
filter_var($_POST['message'], FILTER_SANITIZE_STRING);
function util_array_trim(array &$array, $filter = false)
{
array_walk_recursive($array, function (&$value) use ($filter) {
$value = trim($value);
if ($filter) {
$value = filter_var($value, FILTER_SANITIZE_STRING);
}
});
return $array;
}