1# sanitize form data
2function clean($data)
3{
4 $data = htmlspecialchars($data);
5 $data = stripslashes($data);
6 $data = trim($data);
7 return $data;
8}
1#Filter Validation
2
3<?php
4 //checks for posted data
5 /*
6 if(filter_has_var(INPUT_POST,'data')){
7 echo 'Data Found';
8 }else{
9 echo 'No Data';
10 }
11 */
12 if(filter_has_var(INPUT_POST,'data')){
13 //remove illegal chars
14 $email = $_POST['data'];
15 $email = filter_var($email, FILTER_SANITIZE_EMAIL);
16 echo $email.'<br>';
17
18 //validate as an email address
19 if(filter_input(INPUT_POST, 'data', FILTER_VALIDATE_EMAIL)){
20 echo 'Email is Valid';
21 }else{
22 echo 'Email is not Valid';
23 }
24
25 //we can use the below if we use the sanatizer above
26 if(filter_var($email, FILTER_VALIDATE_EMAIL)){
27 echo 'Email is Valid';
28 }else{
29 echo 'Email is not Valid';
30 }
31}
32 #Other Validations
33 #FILTER_VALIDATE_BOOLEAN
34 #FILTER_VALIDATE_EMAIL
35 #FILTER_VALIDATE_FLOAT
36 #FILTER_VALIDATE_INT
37 #FILTER_VALIDATE_IP
38 #FILTER_VALIDATE_REGEXP 'REGULAR EXPRESSION'
39 #FILTER_VALIDATE_URL
40
41 #Other sanatizes
42 #FILTER_SANATIZE_EMAIL
43 #FILTER_SANATIZE_ENCODED
44 #FILTER_SANATIZE_NUMBER_FLOAT
45 #FILTER_SANATIZE_NUMBER_INT
46 #FILTER_SANATIZE_SPECIAL_CHARS
47 #FILTER_SANATIZE_STRING
48 #FILTER_SANATIZE_URL
49
50 //EXAMPLE int VALIDATION
51 $var = 'john';
52 if(filter_var($var, FILTER_VALIDATE_INT)){
53 echo '<br>'.$var.' is a number<br>';
54 }else{
55 echo '<br>'.$var.' is not a number'.'<br>';
56 }
57
58 //EXAMPLE int Sanitazion
59 $var2 = '33k2dsdffgsdf3563sdf';
60 var_dump(filter_var($var2, FILTER_SANITIZE_NUMBER_INT));
61
62 //ARRAY USAGE
63 $filters = array(
64 "data" => FILTER_VALIDATE_EMAIL,
65 "data2" => array(
66 "filter" => FILTER_VALIDATE_INT,
67 "options" => array(
68 "min_range" => 1,
69 "max_range" => 100
70 )
71 )
72 );
73 print_r(filter_input_array(INPUT_POST, $filters));
74
75?>
76
77<form method ="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
78 <input type="text" name="data">
79 <input type="text" name="data2">
80 <button type="submit">Submit</button>
81</form>