2017-10-12 62 views
-1

我使用数组来允许IP地址谁可以访问,但得到错误的结果时,查询它与数据库。PHP in_array结果不符合预期的IP地址允许的情况下

while($dProfile = oci_fetch_array($qProfile)) 
{ 
    $allowedIP[] = array($dProfile['ALLOWED_IP_ADDRESS']); 
} 

if(in_array($_SERVER['REMOTE_ADDR'], $allowedIP)) 
{ 
    $ip = 1; 
} 
else 
{ 
    $ip = 0; 
} 

echo $ip; 

即使我的IP地址(192.168.183.28)包括在列表中,结果始终为0。

当我print_r($allowedIP)结果是:

Array ([0] => Array ([0] => 192.168.183.205, 192.168.183.28) [1] => Array ([0] => 192.168.184.20, 192.168.184.15)) 

应该得到结果1,因为我的IP地址在数组列表中。

有没有什么窍门如何做到这一点?

+1

你必须含有逗号分隔的字符串数组的数组。 'in_array'不会在数组内的字符串中找到字符串。 – deceze

+0

你应该首先弄平你的阵列,看看https://www.cowburn.info/2012/03/17/flattening-a-multidimensional-array-in-php/ – meta

+0

@deceze让我知道如何去做 –

回答

1

in_array将检查数组的值,在你的情况下它有多个数组值的字符串格式的IP地址。

变化

while($dProfile = oci_fetch_array($qProfile)) 
{ 
    $allowedIP[] = array($dProfile['ALLOWED_IP_ADDRESS']); 
} 

$allowedIP = array(); 
while($dProfile = oci_fetch_array($qProfile)) 
{ 
    $allowedIP = array_merge($allowedIP, array_map('trim', explode(',', $dProfile['ALLOWED_IP_ADDRESS']))); 
} 
2

所以它看起来像$dProfile['ALLOWED_IP_ADDRESS']包含像'192.168.183.205, 192.168.183.28'这样的字符串,然后将其填入数组中的数组中。 in_array不会发现数组中的字符串。你需要首先那些单个地址中的一个平面数组:

while ($dProfile = oci_fetch_array($qProfile)) { 
    $ips = array_map('trim', explode(',', $dProfile['ALLOWED_IP_ADDRESS'])); 
    $allowedIP = array_merge($allowedIP, $ips); 
} 

现在你有IP地址的一个平面列表这in_array可以搜索通过。

但是,由于您首先从数据库中提取这些IP,因此您应该执行简单的数据库查询,而不是在PHP中通过此数组构建和搜索。

-2

试验验证码:

while($dProfile = oci_fetch_array($qProfile)) 
{ 
    $allowedIP[] = array($dProfile['ALLOWED_IP_ADDRESS']); 
} 
if([[$_SERVER['REMOTE_ADDR']]]==$allowedIP) 
{ 
    $ip = 1; 
} 
else 
{ 
    $ip = 0; 
} 

echo $ip; 
0

您应使用此代码:

while($dProfile = oci_fetch_array($qProfile)) 
{ 
    $allowedIps = explode(', ', $dProfile['ALLOWED_IP_ADDRESS']); 
    foreach($allowedIps as $singleAllowedIp) 
    { 
     $allowedIP[] = $singleAllowedIp; 
    } 
} 

代替

while($dProfile = oci_fetch_array($qProfile)) 
 
{ 
 
    $allowedIP[] = array($dProfile['ALLOWED_IP_ADDRESS']); 
 
}