How to check if a string is a valid URL in PHP

When I was working with one Payment gateway, the gateway was simply returning URL string. To complete the transaction, I have to redirect the user to that URL. So in this cases I needed to check if the returned string is valid URL.

<?php

$url = 'https://hackthestuff.com/';

if (filter_var($url, FILTER_VALIDATE_URL)) { 
    echo('valid url');
}

The above function can be more filtered with this filter. This simply check url but if you want to securely validate using regex, here is the below example:

<?php 

$regex = "((https?|ftp)\:\/\/)?";
$regex .= "([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)[email protected])?";
$regex .= "([a-z0-9-.]*)\.([a-z]{2,3})";
$regex .= "(\:[0-9]{2,5})?";
$regex .= "(\/([a-z0-9+\$_-]\.?)+)*\/?";
$regex .= "(\?[a-z+&\$_.-][a-z0-9;:@&%=+\/\$_.-]*)?";
$regex .= "(#[a-z_.-][a-z0-9+\$_.-]*)?";

$url = 'https://hackthestuff.com/';

if (preg_match("/^$regex$/i", $url)) {
   echo('valid url');
}

Here are the basic examples, there may be many ways to check it. If you have to, let us know in the comment below.

Tags: