Skip to main content

Form URL/E-mail

Introduction

Every website requires some form of data input. This could be a search bar, a login form, or a contact form. PHP can help us process this data in a secure and efficient manner. In this tutorial, we will specifically look at how to handle form data that includes URLs and Email addresses.

PHP Form Handling Basics

To process forms in PHP, we use the superglobal variables $_GET or $_POST. These variables are used to collect form data after submitting an HTML form with the method="get" or method="post" attribute.

Let's start with a simple HTML form:

<form method="post" action="handle_form.php">
URL: <input type="text" name="url">
E-mail: <input type="text" name="email">
<input type="submit">
</form>

The method="post" attribute of the form tag tells the browser to send the form data to the server using the HTTP POST method when the user clicks the submit button. The action="handle_form.php" attribute tells the browser to send the form data to the 'handle_form.php' file.

Receiving Form Data

In the 'handle_form.php' file, you can receive the form data using the $_POST superglobal array.

<?php
$url = $_POST['url'];
$email = $_POST['email'];
?>

Validating Form Data

Before processing the form data, it's important to validate it. For this tutorial, we'll focus on validating URLs and Emails.

For URLs, PHP provides the filter_var() function, which can filter and sanitize data. To validate a URL, we use the FILTER_VALIDATE_URL filter:

<?php
$url = $_POST['url'];
if (!filter_var($url, FILTER_VALIDATE_URL)) {
echo("URL is not valid");
} else {
echo("URL is valid");
}
?>

Similarly, to validate an email address, we use the FILTER_VALIDATE_EMAIL filter:

<?php
$email = $_POST['email'];
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo("Email is not valid");
} else {
echo("Email is valid");
}
?>

Conclusion

Well done on making it to the end of this tutorial. You should now have a basic understanding of how to handle form data in PHP, especially data that contains URLs and Emails. Remember to always validate your form data before using it, to ensure that it's safe and in the format you expect. Happy coding!