How to make a validation of php form

Learn how to validate forms with PHP and create secure, user-friendly forms with an easy-to-follow example.

Validating a PHP Form

Validating user input is essential for any web application. Making sure the data submitted by the user is valid before processing it can save time and effort, and help prevent malicious attacks. PHP provides several functions to help you validate user input, such as filter_var(), preg_match(), and filter_input(). In this tutorial, we’ll explore how to use these functions to validate a form submitted using PHP.

Using filter_var()

The filter_var() function is used to validate user input. It takes two parameters, the value to be validated and a filter type. The filter type can be either an integer or a string. For example, if you want to validate an email address, you can use FILTER_VALIDATE_EMAIL as the filter type.

$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);

if ($email === false) {
    // email is not valid
} else {
    // email is valid
}

The filter_var() function will return either false if the value is invalid, or the value itself if it is valid. This makes it easy to check if a value is valid or not.

Using preg_match()

Another useful function for validating user input is preg_match(). This function takes a regular expression as its first parameter and the value to be validated as its second parameter. It then checks if the value matches the regular expression and returns either true or false.

$password = preg_match('/^[A-z0-9]{8,}$/', $_POST['password']);

if ($password) {
    // password is valid
} else {
    // password is not valid
}

In the example above, we are using a regular expression to check if the password is valid. The expression /^[A-z0-9]{8,}$/ checks if the password is at least 8 characters long and contains only letters and numbers.

Using filter_input()

The filter_input() function is similar to filter_var(), but it also takes an optional fourth parameter. This parameter can be used to specify an array of options to use when validating the value. For example, if you want to make sure a number is within a certain range, you can use the min_range and max_range options.

$age = filter_input($_POST['age'], FILTER_VALIDATE_INT, 
    array('min_range' => 18, 'max_range' => 65));

if ($age === false) {
    // age is not valid
} else {
    // age is valid
}

In the example above, we are using the min_range and max_range options to make sure the age is between 18 and 65. If the age is not within this range, the function will return false.

These are just a few of the functions available for validating user input in PHP. You can also use custom validation functions to check for specific conditions. No matter which method you choose, it is important to make sure that your forms are validated before processing the user’s data.

Answers (0)