URL and IP validation functions

Coding Critique is the place to post source code for peer review by other members of DevNetwork. Any kind of code can be posted. Code posted does not have to be limited to PHP. All members are invited to contribute constructive criticism with the goal of improving the code. Posted code should include some background information about it and what areas you specifically would like help with.

Popular code excerpts may be moved to "Code Snippets" by the moderators.

Moderator: General Moderators

Post Reply
User avatar
mikemike
Forum Contributor
Posts: 355
Joined: Sun May 24, 2009 5:37 pm
Location: Chester, UK

URL and IP validation functions

Post 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
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Re: URL and IP validation functions

Post 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.
There are 10 types of people in this world, those who understand binary and those who don't
User avatar
mikemike
Forum Contributor
Posts: 355
Joined: Sun May 24, 2009 5:37 pm
Location: Chester, UK

Re: URL and IP validation functions

Post by mikemike »

Appreciated. Perhaps the function could be renamed. Still a useful tool to have though
Post Reply