Skip to main content

PHP Form Validation

By SamK
0
0 recommends
Category(s)
Topic(s)

In this tutorial, you will learn how to validate form fields of different types in PHP. 

Suppose we have an HTML Form having different fields, where each field has different validation rules as shown below:

  • Name: Required and should only contain letters and spaces.
  • E-mail: Required and should be a valid email address (must include "@" and a domain name).
  • Website: Optional, If provided, and should be a valid URL.
  • Comment: Optional and can accept multiple lines of text (textarea).
  • Gender: Required and the user must select one option.

HTML Form (form.php)

A sample HTML form containing the above form fields is shown below:

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
 <!-- Name Field -->
 <label for="name">Name:</label>
 <input type="text" id="name" name="name" required pattern="[A-Za-z\s]+" placeholder="Enter your name">
 <br>
 <!-- Email Field -->
 <label for="email">E-mail:</label>
 <input type="email" id="email" name="email" required placeholder="Enter your email">
 <br>
 <!-- Website Field -->
 <label for="website">Website:</label>
 <input type="url" id="website" name="website" placeholder="Enter your website URL">
 <br>
 <!-- Comment Field -->
 <label for="comment">Comment:</label>
 <textarea id="comment" name="comment" rows="8" cols="50" placeholder="Enter your comments here"></textarea>
 <br>
 <!-- Gender Field -->
 <span>Gender:</span>
 <input type="radio" id="female" name="gender" value="female" required>
 <label for="female">Female</label>
 <input type="radio" id="male" name="gender" value="male" required>
 <label for="male">Male</label>
 <br>
 <!-- Submit Button -->
 <button type="submit">Submit</button>
</form>

The <form> Element

The HTML code of the form looks like this:

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">

Explanation

When the form is submitted, the form data is sent using the POST method, as specified by the method="post" attribute. This method sends the data in the body of the HTTP request, keeping it hidden from the URL, making it more secure for sensitive information.

The $_SERVER["PHP_SELF"] is a superglobal variable, which is specified in the action attribute, returns the filename of the currently executing script. It allows the form to submit data to the same page from which it was accessed, rather than navigating to a different page. This is useful when you want to display form results or error messages on the same page as the form.

The $_SERVER["PHP_SELF"] variable can pose a security risk if not handled properly, because a user might manipulate the URL by adding a slash (/) followed by potentially harmful Cross-Site Scripting (XSS) commands. This could allow the user to inject and execute malicious scripts on the page, compromising security.

To prevent this risk, always sanitize $_SERVER["PHP_SELF"] using the htmlspecialchars() function. This ensures that any potentially dangerous characters in the URL are converted to their HTML entities, making them harmless.

<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">

If a user enters a standard URL in the address bar, such as http://www.example.com/test_form.php, the code will be translated to:

<form method="post" action="test_form.php">

The htmlspecialchars() function in PHP converts special characters into their corresponding HTML entities. This function is crucial for preventing security vulnerabilities such as Cross-Site Scripting (XSS) attacks by ensuring that user input does not inject malicious HTML or JavaScript code into the page.

Other PHP Form Validation Methods

Use PHP's trim() function to remove unwanted characters, such as extra spaces, tabs, and newlines, from the user input.

Use PHP's stripslashes() function to remove any backslashes (\) from the input.
Next, we will create a function to handle these sanitization checks, making the code more efficient and reusable.

Example:

// Define variables and set them to empty values
$name = $email = $gender = $comment = $website = "";
// Pass each value to test_input() for sanitization
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = test_input($_POST["name"]);
    $email = test_input($_POST["email"]);
    $website = test_input($_POST["website"]);
    $comment = test_input($_POST["comment"]);
    $gender = test_input($_POST["gender"]);
}
// Function to sanitize input data
function test_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}

E-mail and URL Validation

Here’s how to validate E-mail and URL inputs in PHP by using the filter_var() function.

<?php
// Sample input
$email = $_POST['email'];
$url = $_POST['website'];

// Validate email
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "Valid email: $email<br>";
} else {
    echo "Invalid email address<br>";
}

// Validate URL
if (filter_var($url, FILTER_VALIDATE_URL)) {
    echo "Valid URL: $url<br>";
} else {
    echo "Invalid URL<br>";
}
?>

To learn more about the filter_var() function, check our PHP Filters tutorial.

Questions & Answers