PHP code example of cse / helpers-ip

1. Go to this page and download the library: Download cse/helpers-ip library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

cse / helpers-ip example snippets


$ip = IP::getRealIP();
if (IP::isIP($ip)) {
    switch (true) {
        case IP::isIPv4($ip):
            break;
        case IP::isIPv6($ip):
            $ip = IP::removeSubnetMaskIPv6($ip);
            $ip = IP::getRangeIPv6($ip);
            $ip = IP::getFirstIPByVersion($ip);
            break;
    }
    $version = IP::getVersionIP($ip);
}

IP::getRealIP();
// xxx.xxx.xxx.xxx

IP::removeSubnetMaskIPv6('2a0a:2b40::4:60/124');
// 2a0a:2b40::4:60

IP::isIPv4('127.0.0.1');
// true

IP::isIPv4('2a0a:2b40::4:60');
// false

IP::isIPv4('256.256.256');
// false

IP::isIPv6('2a0a:2b40::4:60');
// true

IP::isIPv6('::');
// true

IP::isIPv6('::1');
// true
IP::isIPv6('0:0:0:0:0:0:0:1');
// true

IP::isIPv6('127.0.0.1');
// false

IP::isIPv6(':');
// false

IP::getVersionIP('::1');
// 6

IP::getVersionIP('127.0.0.1');
// 4

IP::getVersionIP('0:0:0:0:0:0:0:1');
// 6

IP::getVersionIP('256.256.256.256');
// null

IP::isIP('::1');
// true

IP::isIP('127.0.0.1');
// true

IP::isIP('0:0:0:0:0:0:0:1');
// true

IP::isIP('256.256.256.256');
// false

IP::getRangeIPv6('2a0a:2b40::4:60/124');
// ['2a0a:2b40::4:60', '2a0a:2b40::4:6f']

IP::filterIPs([
    '127.0.0.1',
    '2a0a:2b40::4:60',
    '255.255.255.255',
    '2a0a:2b40::4:6f',
    '256.256.256.256'
]);
// [4 => ['127.0.0.1', '255.255.255.255'], 6 => ['2a0a:2b40::4:60', '2a0a:2b40::4:6f']]

IP::filterIPs([
    '127.0.0.1',
    '255.255.255.255',
    '256.256.256.256'
]);
// [4 => ['127.0.0.1', '255.255.255.255'], 6 => []]

IP::filterIPs([
    '127.0.0.1',
    '2a0a:2b40::4:60',
    '255.255.255.255',
    '2a0a:2b40::4:6f',
    '256.256.256.256'
], 4);
// ['127.0.0.1', '255.255.255.255']

IP::filterIPs([
    '127.0.0.1',
    '2a0a:2b40::4:60',
    '255.255.255.255',
    '2a0a:2b40::4:6f',
    '256.256.256.256'
], 6);
// ['2a0a:2b40::4:60', '2a0a:2b40::4:6f']

IP::getFirstIPByVersion([
    '256.256.256.256',
    '127.0.0.1',
    '2a0a:2b40::4:60',
    '255.255.255.255',
    '2a0a:2b40::4:6f',
    '256.256.256.256'
], 4);
// '127.0.0.1'

IP::getFirstIPByVersion([
    '256.256.256.256',
    '127.0.0.1',
    '2a0a:2b40::4:60',
    '255.255.255.255',
    '2a0a:2b40::4:6f'
], 6);
// '2a0a:2b40::4:60'
bash
phpunit PATH/TO/PROJECT/tests/
bash
phpunit --configuration PATH/TO/PROJECT/phpunit.xml