Validating a form in PHP
by Lyle, Web Developer
Failure to perform server-side validation on your website can lead webpage form abuse by malicious users.
These malicious attacks usually take the form of SQL injection, cross-site scripting or header injections.
However, these attacks can be prevented by implementing sound server-side validation with either server-side language such as (PHP or Node js) or frameworks such as Laravel, Next js or Express.
HTML form
Makes sure the form element has the following attributes, method and action when setting up a form.
The method attributes specify how the contact form should be submitted.
Top tip
Ideally forms should be submitted using the POST method (sensitive data) unless you want the client to see submitted results in the URL.
The action attribute contains a htmlspecialchars() function and it acts as the first form of server-side sanitizing or user input as it prevents a client from submitting HTML markup or Cross-site Scripting (XSS) attacks in your forms.
The $_SERVER['PHP_SELF'] specifies that the submitted form data must post back to the same script that generated it.
In this case, the data will post back to the page the form is located on.
The form will then consist of two input elements.
Text input field for the client's name and an email input field for the client's email.
The name and value attributes will be used for form processing and returning invalid client input, respectively.
The submit button ensures that a form is submitted and ready for server-side processing.
PHP Form Processing
Ensure that you first declare and define the variables to empty strings.
Thereafter ensure that you create a function (test_input) that will validate the client's input.
Inside the function block your code has to first check client input and whether it contains extra spaces by applying the trim() function.
The stripslashses() function then ensures that backlashes are removed from client input while the htmlspecialchars() function makes sure that HTML characters are converted to their entity names.
Finally, the code block above first checks if the form has been submitted.
Thereafter, ensure that each client input $_POST['variable name'] is validated by enclosing it inside the test_input function and assigned to their respective variable.
Each variable is then checked if it is empty then an error message should be passed and a further regular expression and sanitize of the client input are performed.
Once all checks are completed (each error message is empty) the form will then successfully submit.
In Conclusion
Developers are aware of why it is important to validate user input.
Since users enter the wrong information or act with malicious intent, validating user input is vital.
Following these methods and steps above is a starting block to ensure that you have a sense of security when you are busy developing your system.
Check out my GitHub repository for the full source code.