PHP: URL validation

This entry is part 53 of 54 in the series PHP Tutorial

If we are to validate a web address or URL entered using PHP, we will have to ensure that users will also type in http:// in front of the web address.

<html>
<body>
<form action="" method="post">
    URL (Pls  include http://): <input type="text" name="url"><br><br>
    <input type="submit" name="submit">
</form>
</body>
</html>


<html>
<body>

<?php
$url = @$_POST["url"];

if (isset($_POST['submit'])) {
    if (filter_var($url, FILTER_VALIDATE_URL)) {
        echo "The valid URL is " . $url;
    } else {
        echo "This ($url) web address is considered invalid.";
    }
}
?>

</body>
</html>

You can try entering some URLs in the form here.

PHP: Form email validation

This entry is part 52 of 54 in the series PHP Tutorial

We combine the simple form that we have worked on with the email validation method we have discussed earlier in the previous post.

<html>
<body>

<form action="" method="post">
    Name: <input type="text" name="name"><br>
    E-mail: <input type="text" name="email"><br>
    <input type="submit" name="submit">
</form>

</body>
</html>


<html>
<body>

<?php
$your_name = $_POST["name"];
$your_email = $_POST["email"];

if (isset($_POST['submit'])) {
    echo "Welcome " . $your_name . "<br>";
    if (filter_var($your_email, FILTER_VALIDATE_EMAIL)) {
        echo "Your Email is " . $your_email;
    } else {
        echo "This ($your_email) email address is considered invalid.";
    }
}
?>
</body>
</html>

You can try the code here

PHP: Email validation

This entry is part 51 of 54 in the series PHP Tutorial

A lot of the times, we would need to ensure users have entered the right format of email address.

We can use a function filter_var() provided by PHP to validate emails.

<?php
$email_a = 'joe@example.com';
$email_b = 'bogus';

if (filter_var($email_a, FILTER_VALIDATE_EMAIL)) {
    echo "Your Email is " . $email_a;
    echo "<br><br>";
}

if (filter_var($email_b, FILTER_VALIDATE_EMAIL)) {
    echo "This ($email_b) email address is considered valid.";
} else
    echo "This ($email_b) email address is considered invalid.";
?>

You can try the above code here.