Practical-13
Write a PHP Program to Validate Input Data.
Introduction
Validating user input data is a common task in web development and is an important process to ensure correct and secure data handling. PHP provides multiple access control functions for the validation of user input data and to prevent malicious user access to the server resources. PHP provides various functions such as filter_var(), filter_input(), filter_list() etc. to validate and prevent malicious data input from users. Validating the user input is a must to ensure secure server access and prevent malicious data operations. Proper validation and input validation libraries that help in preventing malicious and incorrect data operations should be used. Lastly, it is important to regularly update PHP libraries and validation scripts to ensure that the user data is handled securely and to prevent any malicious operations.
Code
// Server side validation
// filter inputs
$name = filter_input (INPUT_POST, 'name', FILTER_SANITIZE_STRING);
$age = filter_input (INPUT_POST, 'age', FILTER_SANITIZE_NUMBER_INT);
//Validate inputs
$name = htmlspecialchars($name);
$age = htmlspecialchars($age);
if (!preg_match('/^[a-zA-Z\s]+$/',$name)) {
echo 'Name can only contain letters and spaces.';
exit();
}
if (!preg_match('/^[0-9]+$/', $age)) {
echo 'Age can only be integers.';
exit();
}
Output
Name can only contain letters and spaces.
This code validates user input data in order to prevent malicious user access to server resources. The first two code lines filterinputs for name and age. The if statement validates input data for both name and age and exits if not valid according to the regular expresssion pattern.
Related Resources
- php - Validate and Sanitize Filtered User Input - Stack Overflow
- PHP Filters - W3Schools
- Filter Input in PHP - Tutorialspoint
- PHP Filter Input - Tutorialspoint