簡體   English   中英

在允許 IP 地址的情況下,PHP in_array 結果與預期不符

[英]PHP in_array result not as expected in IP Address allowed case

我正在使用數組來允許可以訪問的 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;

結果始終為 0,即使我的 IP 地址(192.168.183.28)包括在列表中。

當我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 地址在數組列表中。

有什么技巧可以做到這一點嗎?

所以它看起來像$dProfile['ALLOWED_IP_ADDRESS']包含像'192.168.183.205, 192.168.183.28'這樣'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);
}

現在您有了in_array可以搜索的 IP 列表。

但是,由於您首先從數據庫中提取這些 IP,因此您可能應該執行簡單的數據庫查詢,而不是在 PHP 中構建和搜索該數組。

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'])));
}

您應該使用此代碼:

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']); }

測試這段代碼:

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

echo $ip;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM