Backend Development 9 min read

PHP Form Validation Tutorial with Security Best Practices

This article provides a comprehensive PHP form validation tutorial, covering required and optional fields, validation rules using regular expressions, secure handling of user input with trim, stripslashes, and htmlspecialchars, prevention of XSS via $_SERVER['PHP_SELF'] sanitization, and includes complete example code for both the HTML form and processing script.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
PHP Form Validation Tutorial with Security Best Practices

The article explains how to build a secure PHP form that validates user input for fields such as name, email, website, comment, and gender. Required fields must be filled, and each field has specific validation rules (e.g., name must contain only letters and spaces, email must be a valid address, website must be a valid URL).

Server‑side validation is performed in PHP. The script first checks whether the request method is POST, then validates each field, assigning error messages when validation fails. The validation uses regular expressions and the test_input() helper to sanitize data.

<?php // Define variables and set to empty values $nameErr = $emailErr = $genderErr = $websiteErr = ""; $name = $email = $gender = $comment = $website = ""; if ($_SERVER["REQUEST_METHOD"] == "POST") { if (empty($_POST["name"])) { $nameErr = "名字是必需的"; } else { $name = test_input($_POST["name"]); if (!preg_match("/^[a-zA-Z ]*$/", $name)) { $nameErr = "只允许字母和空格"; } } if (empty($_POST["email"])) { $emailErr = "邮箱是必需的"; } else { $email = test_input($_POST["email"]); if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $email)) { $emailErr = "非法邮箱格式"; } } if (empty($_POST["website"])) { $website = ""; } else { $website = test_input($_POST["website"]); if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%%?=~_|!:,.;]*[-a-z0-9+&@#\/%%=~_|]/i", $website)) { $websiteErr = "非法的 URL 的地址"; } } if (empty($_POST["comment"])) { $comment = ""; } else { $comment = test_input($_POST["comment"]); } if (empty($_POST["gender"])) { $genderErr = "性别是必需的"; } else { $gender = test_input($_POST["gender"]); } } function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } ?>

The script uses the super‑global $_SERVER["PHP_SELF"] to set the form’s action attribute, which can be vulnerable to XSS attacks if the value is echoed directly. An attacker could inject a <script> tag via the URL, causing malicious JavaScript to execute when the page is loaded.

To mitigate this risk, the tutorial recommends wrapping $_SERVER["PHP_SELF"] with htmlspecialchars() so that any special characters are converted to HTML entities, preventing script injection.

The helper function test_input() demonstrates the recommended sanitization steps: trim() removes unnecessary whitespace, stripslashes() removes backslashes, and htmlspecialchars() converts characters like <, >, &, ", and ' to their entity equivalents.

Finally, the article provides the HTML form markup that works with the PHP script. The form includes text inputs for name, email, and website, a textarea for comments, and radio buttons for gender. Required fields are marked with an asterisk and error messages are displayed inline.

<form method="post" action=" "> 名字: <input type="text" name="name" value=" "> * E-mail: <input type="text" name="email" value=" "> * 网址: <input type="text" name="website" value=" "> 备注: <textarea name="comment" rows="5" cols="40"> </textarea> 性别: <input type="radio" name="gender" value="female" >女 <input type="radio" name="gender" value="male" >男 * <input type="submit" name="submit" value="Submit"> </form>

By following the steps and code examples in this tutorial, developers can create robust PHP forms that validate input correctly and protect against common web security threats such as cross‑site scripting.

backendsecurityWeb DevelopmentPHPXSSform validation
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.