0

I'm trying to use preg_match to test an URL.

here's a part of my code:

$url_array[0] = $_REQUEST['url0'];
$url_array[1] = $_REQUEST['url1'];
$url_array[2] = $_REQUEST['url2'];
$url_array[3] = $_REQUEST['url3'];
$url_array[4] = $_REQUEST['url4'];

foreach ($url_array as &$val) {
    if(substr($val, 0, 7) != "http://" && substr($val, 0, 8) != "https://" && substr($val, 0, 4) != "www." && $val != "") {
        $val = "http://".$val;
    }
}

foreach ($url_array as &$val) {
    if(!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i", $val) && $val != "") {
    header("Location: {$_SERVER["PHP_SELF"]}?p=home&x=urlerror");
    exit;
    }
}

The problem is it lets through random stuff like http://i'll just use whatever ;G characters here and it'll be fine as an URL. Why is this?

Thanks!
-G

FINAL CONCLUSION:

Regex for URL sorta sucks, I exchanged it for this:

foreach ($url_array as &$val) {
    if(!filter_var($val, FILTER_VALIDATE_URL) === true && $val != "") {
        header("Location: {$_SERVER["PHP_SELF"]}?p=home&x=urlerror");
        exit;
    }
}

And it seems to work perfectly. :)

Thanks to @Passerby and @Chris85

Haxo201
  • 211
  • 1
  • 2
  • 11

0 Answers0