Page 1 of 1

URL and IP validation functions

Posted: Fri Jun 05, 2009 3:50 pm
by mikemike
Source:

Code: Select all

    /* 
     * Check if URL is value
     */
    function isURL($url)
    {
        return preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $url);
    }
    
    /*
     * Check if IP is valid
     */
    function isIP($ip)
    {
        return preg_match("^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}^", $ip);            
    }
Example usage:

Code: Select all

$goodurl = 'http://www.mike-griffiths.co.uk';
$badurl = 'mike.griffiths';
 
$var = isURL($goodurl); // True
$var = isURL($badurl); // False
 
$goodip = '212.220.155.220';
$badip = '256.256.0.256';
 
$var = isIP($goodip); // True
$var = isIP($badip); // False

Re: URL and IP validation functions

Posted: Sun Jun 07, 2009 1:04 pm
by VladSun
Just a quick notice ;)

In general URL is in the form:
The combined syntax looks like:
resource_type://domain:port/filepathname?query_string#anchor
http://en.wikipedia.org/wiki/Uniform_Resource_Locator


So, it's not http/s only.

Re: URL and IP validation functions

Posted: Mon Jun 08, 2009 9:39 am
by mikemike
Appreciated. Perhaps the function could be renamed. Still a useful tool to have though