PHP data filtering tips: How to use the filter_input_array function to batch verify user input
In web development, user input is often not trustworthy. To ensure data security and integrity, we need to validate and filter user input. PHP provides the filter_input_array function, which can help us validate user input in batches.
The filter_input_array function accepts three parameters: the type of input (INPUT_GET, INPUT_POST, INPUT_COOKIE, etc.), the filtering rule array and whether to allow the array as input (INPUT_GET is the default input type). Returns a filtered array, or false if an error occurs.
The following is a sample code that uses the filter_input_array function to batch verify user input:
<?php // 设置输入过滤规则 $filters = array( 'username' => FILTER_SANITIZE_STRING, 'email' => FILTER_VALIDATE_EMAIL, 'age' => array( 'filter' => FILTER_VALIDATE_INT, 'options' => array('min_range' => 18, 'max_range' => 60) ), 'website' => array( 'filter' => FILTER_VALIDATE_URL, 'flags' => FILTER_NULL_ON_FAILURE ) ); // 获取过滤后的输入数据 $input = filter_input_array(INPUT_POST, $filters); // 验证是否发生错误 if ($input === false) { die('输入数据验证失败!'); } // 输出过滤后的输入数据 echo "用户名:" . $input['username'] . "<br>"; echo "邮箱:" . $input['email'] . "<br>"; echo "年龄:" . $input['age'] . "<br>"; echo "个人网站:" . ($input['website'] ?? '未填写') . "<br>"; ?>
In this example, we set up four input filtering rules: username is filtered using FILTER_SANITIZE_STRING, and email is verified using FILTER_VALIDATE_EMAIL , age uses FILTER_VALIDATE_INT to verify and set the value range, website uses FILTER_VALIDATE_URL to verify and sets, and returns null when it fails.
By calling the filter_input_array function and specifying the input type as INPUT_POST, we can obtain the POST data submitted by the user and filter and verify it at the same time. If any input fails validation, the filter_input_array function returns false.
After the verification is passed, we can process and use the filtered data as needed. In the sample code, we output the filtered username, email, age and personal website.
Using the filter_input_array function to batch verify user input can help us effectively reduce the number of verification codes and strengthen the security of the application. At the same time, we can also add custom filtering rules to meet specific needs.
To sum up, by rationally using the filter_input_array function, we can improve our control and security of user input, reduce development time and code volume, and enhance the reliability and robustness of the application.
I hope this article can help you learn how to use the filter_input_array function to verify user input in batches and improve the security and reliability of web applications.
The above is the detailed content of PHP data filtering tips: How to use the filter_input_array function to batch validate user input. For more information, please follow other related articles on the PHP Chinese website!