Codeigniter在库中加载和读取文件

时间:2019-02-14 03:08:08

标签: php codeigniter

我的库文件夹中有一个名为ip_files的文件夹。示例:library/ip_files/0.php ip_files文件夹包含多个文件。查看图片:

enter image description here

我在ip_files文件夹内创建了一个名为GetCountry的类,该类的代码如下:

class GetCountry
{

    public function iptocountry($ip)
    {
        $numbers = preg_split("/\./", $ip);
        echo $numbers[0] . ".php"; //test path

        //I have also tried the below for include path
        //include(base_url()."application/libraries/ip_files/".$numbers[0] . ".php"); 
        //gives a forbidden error

        include($numbers[0] . ".php");
        $code = ($numbers[0] * 16777216) + ($numbers[1] * 65536) + ($numbers[2] * 256) + ($numbers[3]);
        foreach ($ranges as $key => $value) {
            if ($key <= $code) {
                if ($ranges[$key][0] >= $code) {
                    $country = $ranges[$key][1];
                    break;
                }
            }
        }
        return $country;
    }
}

控制器文件夹

   public function index($page = 'index')
   {
    $this->load->library('ip_files/GetCountry'); //load library
    $country = $this->getcountry->iptocountry($_SERVER['REMOTE_ADDR']); //call function
    var_dump($country);

    $this->load->view('templates/head', $data);
    $this->load->view('users/' . $page, $data);
    $this->load->view('templates/footer', $data);
}

我的问题

出现错误Message: include(::1.php): failed to open stream: Invalid argument

在foreach循环中我也得到了一个未定义的偏移量,因为我怀疑该函数的循环路径没有正确打开文件。

任何帮助或建议将不胜感激。 (请记住,我不是CodeIgniter的新手)

2 个答案:

答案 0 :(得分:1)

假设您正在localhost中尝试,这就是$_SERVER['REMOTE_ADDR']返回::1的原因。要获取整数作为文件名,请先从字符串中删除此::符号。

$file_name = str_replace("::","",$numbers[0]);
include($file_name . ".php");

,对于未定义的偏移量问题,请使用isset()函数检查偏移量,如

if(isset($numbers[0])){
   $file_name = str_replace("::","",$numbers[0]);
}

if(isset($ranges[$key][0])){
    if ($ranges[$key][0] >= $code) {
        $country = $ranges[$key][1];
        break;
    }
}

答案 1 :(得分:0)

我的猜测是$ip变量包含IPv6回送地址,通常表示为::1,因此您可以使用带有FILTER_VALIDATE_IP标志的FILTER_FLAG_IPV4来应用仅IPv4的过滤器:< / p>

class GetCountry
{

    public function iptocountry($ip)
    {
        if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
            $numbers = preg_split("/\./", $ip);
            echo $numbers[0] . ".php"; //test path

            //I have also tried the below for include path
            //include(base_url()."application/libraries/ip_files/".$numbers[0] . ".php"); 
            //gives a forbidden error

            include($numbers[0] . ".php");
            $code = ($numbers[0] * 16777216) + ($numbers[1] * 65536) + ($numbers[2] * 256) + ($numbers[3]);
            foreach ($ranges as $key => $value) {
                if ($key <= $code) {
                    if ($ranges[$key][0] >= $code) {
                        $country = $ranges[$key][1];
                        break;
                    }
                }
            }
            return $country;
        }
    }
}