How to check if a string is a valid url?
Snippet Code
This php code is used to check is a string is valid url or not. Regular expression is used here for url validation.
<style>
.errormsg {color: red;}
.errormsg2 {color: green;}
</style>
<?php
error_reporting(0);
$websiteermsg = $websitemsg= $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["website"])) {
$websiteermsg = "URL is required";
} else {
$website = $_POST["website"];
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
$websiteermsg = "Invalid URL";
}
else{
$websitemsg = "Valid URL";
}
}
}
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Enter URL: <input type="text" name="website" value="<?php echo $website; ?>">
<span class="errormsg"><?php echo $websiteermsg;?></span>
<span class="errormsg2"> <?php echo $websitemsg;?></span>
<div><input type="submit" name="submit" value="Check"></div>
</form>
Tags