0

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";
    }
AbraCadaver
  • 77,023
  • 7
  • 60
  • 83
Roxx
  • 3,266
  • 16
  • 75
  • 140

2 Answers2

5

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";
}
AbraCadaver
  • 77,023
  • 7
  • 60
  • 83
  • Your solution is correct. I was stupid to checking regex. Its so easy. Thanks Voted up. – Roxx Aug 30 '16 at 18:36
0

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

Abhijit Jagtap
  • 2,605
  • 2
  • 31
  • 42
  • i want only one condition to be correct (http://www.google.com) rest should be invalid. – Roxx Aug 30 '16 at 18:33