RT Cunningham

My PHP Code Library - Functions and Other PHP Routines

php codeWith the PHP code I’m displaying today, I’m not trying to make a point of any kind. I’m sharing functions and other PHP routines, so I don’t have to keep moving them with a document from place to place.

The code isn’t perfect. I’m sure some of it could be better, but I’m way too lazy to work on it.

Function: CIDR Match

With this function, you can find out if a specific IP address falls within a specified range. It comes in real handy when you need to check hundreds of IP addresses against dozens of ranges.

function cidr_match($ip, $cidr)
{
    if (!strpos($cidr, '/'))
    {
        if ($ip == $cidr)
        {
            return true;
        }
        return false;
    }
    list($subnet, $mask) = explode('/', $cidr);
    if ((ip2long($ip) & ~ (( 1 << (32 - $mask)) - 1)) == ip2long ($subnet))
    {
        return true;
    }
    return false;
}

Function: String Replace First

I found this function when I was searching for a way to replace only the first occurrence on a page. For me, it’s simpler than using preg_replace (and probably faster):

function str_replace_first($search, $replace, $subject)
{
    $pos = strpos($subject, $search);
    if ($pos !== false)
    {
        return substr_replace($subject, $replace, $pos, strlen($search));
    }
    return $subject;
}

HTML and PHP Code: Timezone Dropdown List

This is merely demonstration code. It should be simple to follow:

In this example, you could use date_default_timezone_set($_POST[‘timezone’]) to set the timezone.

Share:    

RT Cunningham
September 30, 2019 3:59 pm
Web Development