Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,880 questions

51,806 answers

573 users

How to validate URL in HTML form with PHP

1 Answer

0 votes
<!DOCTYPE HTML>
<html>
<head>
<style>
.error_message {color: #FF0000;}
</style>
</head>
<body>
<?php
$err_msg = "";
$url = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") 
{
    if (empty($_POST["url"])) 
    {
        $url = "";
    } 
    else 
    {
        $url = clean_input($_POST["url"]);
        // check if URL is valid
        if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i", $url)) 
        {
            $err_msg = "Invalid URL";
        }
        else
            $err_msg = "";
   }
}
function clean_input($data) 
{
   $data = trim($data);
   $data = stripslashes($data);
   $data = htmlspecialchars($data);
   
   return $data;
}
?>
<h3>Form Validation With PHP</h3>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
   URL: <input type="text" name="url">
   <span class="error_message">* <?php echo $err_msg;?></span>
   <br /><br />
   <input type="submit" name="submit" value="Submit">
</form>
<?php
echo "URL = " . $url;
?>
</body>
</html>

 



answered Nov 24, 2015 by avibootz
edited Nov 24, 2015 by avibootz

Related questions

2 answers 272 views
272 views asked Nov 19, 2018 by avibootz
1 answer 195 views
1 answer 180 views
2 answers 4,746 views
...