Validate URL in PHP with multiple methods

While taking URL as user input, it’s essential to validate it properly; otherwise, it can affect the application. In this article, we will Validate URL in PHP with Multiple Method such as regular expressions and the FILTER_VALIDATE_URL function. You can also implement these methods in other PHP-based frameworks like Laravel or CI.

Here, we will see two methods. Both check URL is valid or not using PHP functionality.

  • Validate URL Using Regex
  • Validate URL Using Filter (FILTER_VALIDATE_URL)

The preg_match() regular expression is aimed to search patterns into strings. It will return true if a match is found otherwise, false. While in other methods, we will use the filter function. This function is used to filter the variable’s value by per-defined filters. Here, we will use a URL validation filter.

Validate URL Using Regex

Regex methods just work like search with some specific conditions or we can say multiple search terms into one value. For this example, we will define our URL statically. You can take URL as user input as per your requirement.

<?php
    $urlToValidate = "https://www.codewolfy.com";
    if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$urlToValidate)) {
        echo "Invalid URL";
    }else{
        echo "Valid URL";
    }
?>

Validate URL Using Filter

PHP provides filter_var() inbuilt function with FILTER_VALIDATE_URL filter. Here, we just have to pass the URL and it will automatically validate and return the status. There are a few flags like FILTER_FLAG_HOST_REQUIRED or FILTER_FLAG_PATH_REQUIRED which you can use as per your requirements.

<?php
    $urlToValidate = "https://www.codewolfy.com";
    if (!filter_var($urlToValidate, FILTER_VALIDATE_URL) === false) {
        echo "Valid URL";
    } else {
        echo "Invalid URL";
    }
?>

Conclusion

In this article, we have validated URLs using filter functions and regular expressions. The filter method is idle for this purpose because of the flag and it’s easy to implement.

For checking the validity of user emails in PHP, Validate Email Address In PHP With Multiple Ways explains different methods like regex and built-in PHP filters to ensure accurate email validation.