PHP form validation
PHP Form Validation
In this chapter we will introduce how to use PHP to verify form data submitted by the client.
User input should be validated (via client script) whenever possible. Browser validation is faster and reduces the load on the server.
If user input needs to be inserted into the database, you should consider using server validation. A good way to validate a form on the server is to pass the form to itself, rather than jumping to a different page. This way users can get error messages on the same form page. It will be easier for users to find errors.
#We need to consider security when processing PHP forms.
In this chapter we will demonstrate the secure processing of PHP form data. In order to prevent hackers and spam, we need to perform data security verification on the form.
PHP form validation example
The above form uses the following validation rules:
##First let’s take a look at the pure HTML code of this form:Text field
name, email and website are text input elements, and the comment field is a text box. The HTML code is like this:Name: E-mail: Website: Comment:
Radio button
gender field is single Select button, the HTML code is like this:Gender: Female Male
Form element
The HTML code for the form is like this:This code adds a script and a prompt command. And when the page loads, the JavaScript code will be executed (the user will see a tooltip). This is just a simple and harmless example of how the PHP_SELF variable can be exploited.
You should realize that you can add any JavaScript code inside the
Now this code is displayed on the page or in the e-mail is safe.
When the user submits the form, we have to do two more things:
1. (Through the PHP trim() function) Remove unnecessary characters (extra spaces) in the user input data , tab character, newline)
2. (Through PHP stripslashes() function) Remove backslashes (\) in user input data
Next we create a check function (similar to This is more efficient than writing code over and over again).
We named the function test_input().