PHP - Проверка электронной почты и URL

Привет, начинающие разработчики PHP! Сегодня мы окунемся в fascинирующий мир проверки форм, конкретно focusing на проверке электронной почты и URL. Как кто-то, кто teaches PHP уже более десяти лет, я не могу не stress, насколько важна эта тема. Поверьте мне, вы поблагодарите меня позже, когда будете создавать robust веб-приложения!

PHP - Form Email/URL

Why Validate Email and URL?

Before we jump into the nitty-gritty, let's talk about why we need to validate emails and URLs in the first place. Imagine you're building a contact form for a client's website. You want to make sure that when users submit their email addresses, they're actually giving you valid ones. Otherwise, you might end up with a database full of "[email protected]" or "notanemail" entries. Not very helpful, right?

The same goes for URLs. If you're asking users to input their website address, you want to ensure it's in the correct format. Otherwise, you might end up trying to redirect your users to "www.ilovepizza" (which, sadly, isn't a real website... yet).

Validation with Regex

Our first weapon of choice in the battle against invalid inputs is the mighty Regular Expression, or Regex for short. Don't worry if that sounds intimidating – I promise it's not as scary as it looks!

Email Validation with Regex

Let's start with a simple example of email validation using regex:

<?php
$email = "[email protected]";
$pattern = '/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/';

if (preg_match($pattern, $email)) {
echo "Valid email address!";
} else {
echo "Invalid email address!";
}
?>

Let's break this down:

  1. We start by defining our email and the regex pattern.
  2. The preg_match() function checks if our email matches the pattern.
  3. If it matches, we consider it valid; otherwise, it's invalid.

But what does that pattern mean? Let's dissect it:

  • ^ : Начало строки
  • [a-zA-Z0-9._%+-]+ : Один или несколько символов: букв, чисел или определенных специальных символов
  • @ : Лiteral "@" symbol
  • [a-zA-Z0-9.-]+ : Один или несколько символов: букв, чисел, точек или тире
  • \. : Лiteral dot
  • [a-zA-Z]{2,} : Две или более букв
  • $ : Конец строки

URL Validation with Regex

Now, let's tackle URL validation:

<?php
$url = "https://www.example.com";
$pattern = '/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/';

if (preg_match($pattern, $url)) {
echo "Valid URL!";
} else {
echo "Invalid URL!";
}
?>

This pattern is a bit more complex, but the principle is the same. It checks for the typical components of a URL: protocol (optional), domain name, top-level domain, and path (optional).

Using filter_var() function

While regex is powerful, PHP provides us with a built-in function that can make our lives even easier: filter_var(). This function is specifically designed to validate and sanitize data.

Email Validation with filter_var()

Here's how we can use filter_var() to validate an email address:

<?php
$email = "[email protected]";

if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Valid email address!";
} else {
echo "Invalid email address!";
}
?>

Isn't that neat? No complex regex patterns to remember – PHP does the heavy lifting for us!

URL Validation with filter_var()

Similarly, we can validate URLs:

<?php
$url = "https://www.example.com";

if (filter_var($url, FILTER_VALIDATE_URL)) {
echo "Valid URL!";
} else {
echo "Invalid URL!";
}
?>

Comparing Methods

Now that we've seen both methods, let's compare them:

Method Pros Cons
Regex Highly customizable Can be complex to write and maintain
Powerful pattern matching Might be overkill for simple validations
filter_var() Easy to use Less flexible than regex
Built-in PHP function Limited to predefined validation types
Generally faster than regex

Practical Application

Let's put it all together with a simple form that validates both email and URL:

<!DOCTYPE html>
<html>
<body>

<h2>Contact Form</h2>

<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
E-mail: <input type="text" name="email"><br>
Website: <input type="text" name="website"><br>
<input type="submit">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$email = $_POST['email'];
$website = $_POST['website'];

if (filter_var($email, FILTER_VALIDATE_EMAIL) && filter_var($website, FILTER_VALIDATE_URL)) {
echo "Both email and website are valid!";
} else {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Invalid email address.<br>";
}
if (!filter_var($website, FILTER_VALIDATE_URL)) {
echo "Invalid URL.";
}
}
}
?>

</body>
</html>

This script creates a simple HTML form and then validates the submitted email and URL using filter_var(). If either input is invalid, it provides specific feedback to the user.

Conclusion

And there you have it, folks! We've covered two powerful methods for validating emails and URLs in PHP. Remember, validation is crucial for maintaining data integrity and improving user experience. Whether you choose the flexibility of regex or the simplicity of filter_var(), you're now equipped to handle user inputs like a pro!

As always, practice makes perfect. Try creating your own forms and experimenting with different validation techniques. And remember, in the world of web development, there's always more to learn. Keep coding, keep exploring, and most importantly, keep having fun!

Credits: Image by storyset