PHP Form URL/Email

PHP Form URL/Email


Form Validate Email :A valid email must contain @ and . symbols. PHP provides various methods to validate the email address. Here, we will use regular expressions to validate the email address.

Form Validate URL :The below code validates the URL of website provided by the user via HTML form. If the field does not contain a valid URL, the code will display an error message, i.e., "URL is not valid".

 Example  of validate Email and URL :                   

<html>
    <body>
       <?php
      $emailErr=$urlErr = "";
      $email = $url = "";
        if ($_SERVER["REQUEST_METHOD"] == "POST") {
            if (empty($_POST["email"])) {
                $emailErr = "Email is required";
              } else {
                $email = test_input($_POST["email"]);
                // check if e-mail address is well-formed
                if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                  $emailErr = "Invalid email format";
                }
              }
               if (empty($_POST["url"])) {
                $url = "";
              } else {
                $url = test_input($_POST["url"]);
                // check if URL address syntax is valid
                if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-                      9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$url)) {
                  $urlErr = "Invalid URL";
                }    
              }
            }
              function test_input($data) {
                $data = trim($data);
                $data = stripslashes($data);
                $data = htmlspecialchars($data);
                return $data;
              }
    ?>
     <h2>Form URL/Email</h2>
     <p><span class="error">* required field</span></p>
     <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
            Email : <input type="text" name="email">
            <span class="error">* <?php echo $emailErr;?></span><br><br>
            URl :<input type="text" name="url">
            <span class="error"><?php echo $urlErr;?></span><br>
            <input type="submit" name="submit" value="Submit">
        </form>
     <?php
     echo  "<h2>Your Input:</h2>";
      echo $email;
      echo "<br>";
      echo $url;
      echo "<br>";  
     ?>
    </body>
   </html>

Output : invalid Email/URL

Valid Email/URL :