Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP URL verification and if not valid fix it

Tags:

php

I am trying to verify URLs. This is the code I have:

function isValidURL($url) 
{
    return preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $url);
}

This code is working but now I am trying to work out how to add http:// or https:// if the URL is correct but is just missing the beginning http://

Please point me in the right direction.

like image 473
DCSoft Avatar asked Dec 16 '22 13:12

DCSoft


2 Answers

Use the filter functions, there's a FILTER_VALIDATE_URL for this.

$is_valid_url = filter_var($url, FILTER_VALIDATE_URL);

There's a bunch of options too, see here.

To detect if there's a missing http:// or not, just test your input without modifying it first, and try prepend it and test again if that fails.

like image 91
complex857 Avatar answered Jan 01 '23 01:01

complex857


You can use parse_url() to verify your url http://php.net/manual/en/function.parse-url.php

<?php

$url = "https://twitter.com?id=3232";
$url_info = parse_url($url);

echo "<pre>";
    print_r($url_info);
echo "</pre>";


?>

Output

Array
(
    [scheme] => https
    [host] => twitter.com
    [query] => id=3232
)

I believe you can even work with this function parse_url you will get lot of parameters easily and understandable format.

so your code will be

<?php

function isValidURL($url) {
    $varr = parse_url($url);
    if ($varr['scheme'] == 'https') {
        return true;
    }
    return false;
}
?>

Note : Url used above is not valid, its for testing purspose

like image 23
Rafee Avatar answered Jan 01 '23 01:01

Rafee