48. Form Validation and Data Sanitization
Never trust user input. Before processing or storing data, you must validate (check if it meets requirements) and sanitize (clean up harmful characters).
1. Validation (Checking Requirements)
Validation ensures data is in the correct format, type, and length. PHP provides built-in functions for this.
| Function | Description |
|---|---|
empty($var) | Checks if a variable is empty (0, empty string, null, false). |
filter_var($var, FILTER_VALIDATE_EMAIL) | Checks if the input is a valid email format. |
is_numeric($var) | Checks if the input is a valid number. |
php
2. Sanitization (Cleaning Input)
Sanitization removes illegal characters from user input to prevent attacks (like XSS).
| Function | Description |
|---|---|
trim() | Removes leading/trailing whitespace. |
strip_tags($str) | Removes HTML and PHP tags from a string. |
htmlspecialchars($str) | Converts special characters to HTML entities, crucial for outputting user data safely. |
filter_var($var, FILTER_SANITIZE_STRING) | Removes or encodes characters that are not permitted in a string. |
php
alert('xss') Hello World"; // Sanitize by removing tags $clean_data = strip_tags($unsafe_input); echo $clean_data; // Output: Hello World // When outputting user input to HTML, always escape it $safe_output = htmlspecialchars($unsafe_input); // The browser displays the text, but doesn't execute the script ?>