i

PHP Tutorial

PHP Form Validation

If we are allowing user to enter a URL and we need to check if it is a valid URL or not we can write the below code in php,

$input_website = input($_POST["website"]);

if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {

   $website_Error = "Invalid URL";

   echo “$website_Error”;

}

The above code checks the input from the form and validates the URL should have letters, symbols and start with www, ftp, https etc. If it is not matching then an error saying Invalid URL is printed.