简体   繁体   中英

PHP - How to use config file variables in a function's array?

I could not find an example of what I'm trying to accomplish. I guess I don't know the proper search words to use. I have a working script but I want to make it more flexible by adding a main, admin editable config file.

I have the following function:

    function ip_is_mobile($ip) {
        $pri_addrs = array(                 
            '66.87.0.0-66.87.255.255',  // Sprint mobile
            '174.192.0.0-174.255.255.255'   // Verizon mobile
        );
    
        $long_ip = ip2long($ip);
    
        if($long_ip != -1) {

            foreach($pri_addrs AS $pri_addr) {
                list($start, $end) = explode('-', $pri_addr);

                // IF IS a mobile IP
                if($long_ip >= ip2long($start) && $long_ip <= ip2long($end))
                    return true;
            }
        }
        return false;
    }

I would like to replace the hard-coded IP address ranges, in the function, with variables or definitions which will be set in the main config file so that the config file has something similar to the following:

// Mobile IP address ranges. Add as many as needed.
$MobileIPs['0']="66.87.0.0-66.87.255.255";
$MobileIPs['1']="174.192.0.0-174.255.255.255";
$MobileIPs['2']="85.110.50.0/24";

My goal is to give the admin an easy to read and understand way of adding as many IP address ranges as necessary (probably 20 max). I'm not opposed to totally rewriting the function if there is a better, more efficient way. In addition to IP ranges, it would be advantageous if CIDR's could also be specified; as indicated in the last code line above.

What edits do I need to make to the function and what would the corresponding lines in the main config file be so that the user can add any number of ranges or CIDR's?

You can store configuration of ip ranges in separate configuration file and use require_once in your main code

ip_ranges.conf.php (configuration file)

<?php

    $pri_addrs = array(                 
        '66.87.0.0-66.87.255.255',    // Sprint mobile
        '174.192.0.0-174.255.255.255' // Verizon mobile
    );

index.php (main code file)

function ip_is_mobile($ip) {
    require_once(ip_ranges.conf.php); // include config file

    $long_ip = ip2long($ip);

    if($long_ip != -1) {
        foreach($pri_addrs AS $pri_addr) {
            list($start, $end) = explode('-', $pri_addr);
                 
             // IF IS a mobile IP
             if($long_ip >= ip2long($start) && $long_ip <= ip2long($end))
            return true;
        }
    }
    return false;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM