PHP - Проверка форм
Здравствуйте,野心勃勃 PHP разработчики! Сегодня мы окунемся в захватывающий мир проверки форм. Как ваш доброжелательный соседний компьютерный учитель, я здесь, чтобы направить вас через этот важный аспект веб-разработки. Поверьте мне, овладение проверкой форм похоже на обучение езде на велосипеде - как только вы это поймете, вы никогда не забудете!
Why Form Validation Matters (Why Form Validation Is Important)
Before we jump into the code, let's talk about why form validation is so important. Imagine you're running a pizza delivery service online. If someone orders 'ABC' pizzas or enters '-5' as their phone number, you'd be in quite a pickle! That's where form validation comes to the rescue, ensuring that the data you receive is correct and usable.
Client-side vs. Server-side Validation (Client-side vs. Server-side Validation)
In the world of form validation, we have two main players: client-side and server-side validation. Today, we'll focus on server-side validation using PHP, but let's briefly touch on both:
Client-side Validation (Client-side Validation)
Client-side validation happens in the user's browser before the data is sent to the server. It's quick and provides instant feedback, but it can be bypassed by savvy users.
Server-side Validation (Server-side Validation)
Server-side validation occurs on the server after the form is submitted. It's more secure and reliable, as users can't tamper with it. This is what we'll be exploring in depth today.
Getting Started with PHP Form Validation (Getting Started with PHP Form Validation)
Let's start with a simple form and build our validation step by step. Here's our basic HTML form:
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="age"><br>
<input type="submit" name="submit" value="Submit">
</form>
Now, let's add some PHP magic to validate this form!
Validation Functions (Validation Functions)
Before we dive into specific validations, let's create some helper functions:
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
This test_input()
function does three important things:
-
trim()
removes whitespace from both sides of a string -
stripslashes()
removes backslashes -
htmlspecialchars()
converts special characters to HTML entities
These steps help prevent malicious code injection and ensure our data is clean.
Form is Empty (Form is Empty)
Let's start with a basic check: is the form empty? Here's how we can do that:
<?php
$name = $age = "";
$nameErr = $ageErr = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["age"])) {
$ageErr = "Age is required";
} else {
$age = test_input($_POST["age"]);
}
}
?>
In this code:
- We initialize variables to store our form data and error messages.
- We check if the form was submitted using POST.
- For each field, we check if it's empty. If it is, we set an error message. If not, we clean the input using our
test_input()
function.
Age field is non-numeric (Age field is non-numeric)
Now, let's add a specific check for the age field to ensure it's a number:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// ... previous checks ...
if (empty($_POST["age"])) {
$ageErr = "Age is required";
} else {
$age = test_input($_POST["age"]);
if (!is_numeric($age)) {
$ageErr = "Age must be a number";
}
}
}
Here, we've added an extra check using is_numeric()
to ensure the age is actually a number. If it's not, we set an appropriate error message.
Putting It All Together (Putting It All Together)
Now, let's see how our complete form validation script looks:
<?php
$name = $age = "";
$nameErr = $ageErr = "";
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["age"])) {
$ageErr = "Age is required";
} else {
$age = test_input($_POST["age"]);
if (!is_numeric($age)) {
$ageErr = "Age must be a number";
}
}
}
?>
<h2>PHP Form Validation Example</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<span class="error"><?php echo $nameErr;?></span>
<br><br>
Age: <input type="text" name="age">
<span class="error"><?php echo $ageErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $age;
?>
This script:
- Defines variables and functions
- Validates the form when submitted
- Displays the form with error messages if any
- Shows the validated input
Validation Methods Table (Validation Methods Table)
Here's a handy table of common validation methods in PHP:
Method | Description | Example |
---|---|---|
empty() | Checks if a variable is empty | if (empty($var)) |
isset() | Checks if a variable is set and is not NULL | if (isset($var)) |
is_numeric() | Checks if a variable is a number or a numeric string | if (is_numeric($var)) |
strlen() | Gets the length of a string | if (strlen($var) > 5) |
preg_match() | Performs a regular expression match | if (preg_match("/pattern/", $var)) |
filter_var() | Filters a variable with a specified filter | if (filter_var($var, FILTER_VALIDATE_EMAIL)) |
Remember, form validation is all about ensuring data integrity and improving user experience. It's like being a bouncer at a club - you want to let the good data in and keep the bad data out!
As we wrap up, I hope this tutorial has given you a solid foundation in PHP form validation. Remember, practice makes perfect, so don't be afraid to experiment with different forms and validation techniques. Before you know it, you'll be validating forms like a pro!
Happy coding, and may your forms always be valid!
Credits: Image by storyset