1 <?php
2// define variables and set to empty values
3$name = $email = $gender = $comment = $website = "";
4
5if ($_SERVER["REQUEST_METHOD"] == "POST") {
6 $name = test_input($_POST["name"]);
7 $email = test_input($_POST["email"]);
8
9
10 $website = test_input($_POST["website"]);
11 $comment = test_input($_POST["comment"]);
12 $gender = test_input($_POST["gender"]);
13}
14
15 //php form data validation function
16function test_input($data) {
17 $data = trim($data);
18 $data = stripslashes($data);
19 $data = htmlspecialchars($data);
20 return $data;
21
22 }
23?>
1<?php
2
3class Input {
4 static $errors = true;
5
6 static function check($arr, $on = false) {
7 if ($on === false) {
8 $on = $_REQUEST;
9 }
10 foreach ($arr as $value) {
11 if (empty($on[$value])) {
12 self::throwError('Data is missing', 900);
13 }
14 }
15 }
16
17 static function int($val) {
18 $val = filter_var($val, FILTER_VALIDATE_INT);
19 if ($val === false) {
20 self::throwError('Invalid Integer', 901);
21 }
22 return $val;
23 }
24
25 static function str($val) {
26 if (!is_string($val)) {
27 self::throwError('Invalid String', 902);
28 }
29 $val = trim(htmlspecialchars($val));
30 return $val;
31 }
32
33 static function bool($val) {
34 $val = filter_var($val, FILTER_VALIDATE_BOOLEAN);
35 return $val;
36 }
37
38 static function email($val) {
39 $val = filter_var($val, FILTER_VALIDATE_EMAIL);
40 if ($val === false) {
41 self::throwError('Invalid Email', 903);
42 }
43 return $val;
44 }
45
46 static function url($val) {
47 $val = filter_var($val, FILTER_VALIDATE_URL);
48 if ($val === false) {
49 self::throwError('Invalid URL', 904);
50 }
51 return $val;
52 }
53
54 static function throwError($error = 'Error In Processing', $errorCode = 0) {
55 if (self::$errors === true) {
56 throw new Exception($error, $errorCode);
57 }
58 }
59}
60
1<label for="name">Name</label>
2 <div>
3 <input type="text" name="name" id="name" value="">
4 </div>
5
6<label for="address">Address</label>
7 <div>
8 <input type="text" name="address" id="address" value="">
9 </div>
10
11<label for="email">Email</label>
12 <div>
13 <input type="text" name="email" id="email" value="">
14 </div>
15
16
17
1<?php
2
3if ($_SERVER['REQUEST_METHOD'] === 'POST') {
4
5 // the request method is fine
6
7} else {
8
9 exit('Invalid Request');
10
11}
12