2017-10-12 63 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']); 
 
}