Roxx
Roxx

Reputation: 3986

URL validation must contain http or https

I am searching multiple websites to fix this issue. The problem is I am asking user to enter website address and like people says never trust user input.

So, possible scenario can be like this:

https or http://www.google.com

https or http://google.com

www.google.com

google.com

Now I want URL must be like this. http or https//www.google.com

At the moment I have below code but it is not working as expected.

$url = "www.google.com";    
if (preg_match("/\b(?:(?:https?):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i", $url)) {
      echo "URL is valid";
    }
    else {
      echo "URL is invalid";
    }

Upvotes: 0

Views: 2535

Answers (2)

AbraCadaver
AbraCadaver

Reputation: 78994

Check if the start of the string contains http which also includes https AND check if it's a valid URL:

if((strpos($url, 'http') === 0) && filter_var($url, FILTER_VALIDATE_URL)) {
    echo "URL is valid";
} else {
    echo "URL is invalid";
}

Upvotes: 5

Abhijit Jagtap
Abhijit Jagtap

Reputation: 2702

Try this Expression

/[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi

It will aceept all the cases that you have mentioned above

Upvotes: 0

Related Questions