The primary goal of form validation is security. Hackers often try to send malicious scripts through form fields. Therefore, it is essential to "Sanitize" and "Validate" every piece of data sent by the user.
Often, we use $_SERVER["PHP_SELF"] in the form's action attribute so that the form submits to the same page. However, if this is not sanitized, a hacker can inject scripts through the URL (known as a Cross-Site Scripting or XSS Attack).
Instead of writing the same cleaning code for every field, it is better to create a reusable function to clean the data:
When the form is submitted, we pass every input variable through our test_input() function:
During validation, we typically check for these three things:
htmlspecialchars(). This function converts tags like <script> into <script>, ensuring the browser treats it as plain text instead of executing it.