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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With