我的库文件夹中有一个名为ip_files的文件夹。示例:library/ip_files/0.php
ip_files文件夹包含多个文件。查看图片:
我在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的新手)
答案 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;
}
}
}