PHP代码过滤:使用filter_input时check_input函数是否冗余或有误?
Great question—let’s unpack this clearly, since it depends entirely on what your check_input() function actually does and how you’re using filter_input().
First, Let’s Define the Context
You mentioned this code runs after a form submit: you’re using filter_input() to handle input, then possibly passing that result through check_input(). The key is comparing the specific behavior of both tools.
Scenario 1: check_input() Duplicates filter_input()’s Work (Redundant, Even Risky)
Suppose your check_input() looks like this super common custom sanitization function:
function check_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; }
And you’re using filter_input() with a filter that covers the same ground, like:
$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
FILTER_SANITIZE_FULL_SPECIAL_CHARSalready handles the equivalent ofhtmlspecialchars()(it escapes quotes, ampersands, angle brackets, etc.)- If you then run
$username = check_input($username);, you’re double-escaping characters (e.g.,&becomes&then&), which breaks display of user input. That’s not just redundant—it’s an error. - Even
trim()might be redundant if you’re using a filter likeFILTER_SANITIZE_STRING(though some filters don’t handle whitespace, so you’ll need to verify the filter’s behavior).
Scenario 2: check_input() Adds Unique Value (Not Redundant)
If check_input() handles logic that filter_input() can’t or doesn’t cover, it’s a necessary complement. For example:
function check_input($data) { // Enforce business-specific rules if (strlen($data) < 3 || strlen($data) > 20) { return false; } // Remove non-alphanumeric characters that filter_input didn't catch $data = preg_replace('/[^a-zA-Z0-9_]/', '', $data); // Trim extra internal spaces (filter_input doesn't do this by default) $data = preg_replace('/\s+/', ' ', $data); return $data; }
Here, filter_input() handles basic sanitization (like escaping for XSS), while check_input() enforces your app’s unique input rules. This is not redundant—it’s layered filtering that makes your input more secure and consistent.
Key Takeaways
- Audit both tools: Compare every line of
check_input()against the filter you’re using withfilter_input()(look up the exact behavior of your chosen filter in PHP’s official documentation). - Avoid double-sanitization: Duplicating escaping (like
htmlspecialchars()twice) will corrupt user input. - Leverage
filter_input()’s strengths: It pulls data directly from the input source (bypassing potentially tainted global variables like$_POST), which is more secure than grabbing data first then sanitizing. - Use
check_input()for custom logic: Reserve it for business rules, custom pattern matching, or cleanup that built-in filters don’t handle.
内容的提问来源于stack exchange,提问作者oxk4r

