Forms are used everywhere in development to store data in the backend. In PHP, form variables defined in the context are linked to the form elements, and a post-action is created to submit the form in the storage. We will first see some elements that use form validation and deal with the security issue.
Let us create a form with the below-mentioned fields
Name
Must contain only letter and whitespaces and is required
Email
Must be in email format and is required
Profile Link
Should be a link
Message
No rule
Slot
One must be selected
Text Fields
The below code illustrates name, email, profile link, message fields as text input. To take multiple text input lines, one can use textarea and specify the lines of rows and columns they need.
The hacker injected an unwanted script into the page. Now he can exploit information from the site. As he gains access, the javascript code injected is capable to scrap out critical information of the user like passwords, files and card information.
How to avoid it?
Using htmlspecialchars($_SERVER[“PHP_SELF]) can handle such attacks. It works by converting quotations,brackets to HTML entities like " , >, <. Now if the hacker tries to inject his script. The code will get converted to HTML.
It is a security vulnerability in web applications in which the hacker would inject scripts into the user's page to scrap out information or do anything with the information.
What is $_SERVER["PHP_SELF"]?
This variable returns the filename of the current script under execution.
What is the use of htmlspecialchars() function?
The htmlspecialchars() function is an inbuilt PHP function. Certain predefined characters are converted to HTML entities using the htmlspecialchars() function. Some of the examples of predefined characters are " (double quote), ' (single quote), and & (ampersand).
Conclusion
Congratulations on getting through this article, we went through setting up a form for validation and used htmlspecialchars to help eliminate exploits. In the next article, you will see how to create error messages, validations in email and much more.
You can take a look at our PHP archives section and see many more interesting topics related to it.
Live masterclass
Switch from non tech to high paying data analytics profile
by Alka Pandey, Data Scientist @ Hindustan Unilever
09 Oct, 2024
01:30 PM
Master PowerBI using Netflix Data
by Ashwin Goyal, Product @ HRS Group, Ex - Udaan, OYO
08 Oct, 2024
01:30 PM
Switch from non tech to high paying data analytics profile
by Alka Pandey, Data Scientist @ Hindustan Unilever
09 Oct, 2024
01:30 PM
Master PowerBI using Netflix Data
by Ashwin Goyal, Product @ HRS Group, Ex - Udaan, OYO