I'm using array to allow IP Address who can access, but got wrong result when query it with database.
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;
The result is always 0 even my IP Address(192.168.183.28) including in the list.
When I print_r($allowedIP)
the result is:
Array ( [0] => Array ( [0] => 192.168.183.205, 192.168.183.28 ) [1] => Array ( [0] => 192.168.184.20, 192.168.184.15 ) )
It should be got result 1, because my IP Address is in the list of array.
Is there any trick how to do that?
So it looks like $dProfile['ALLOWED_IP_ADDRESS']
contains strings like '192.168.183.205, 192.168.183.28'
, which you're then stuffing into arrays in an array. in_array
is not going to discover strings in strings in arrays. You need to make one flat array of all those individual addresses first:
while ($dProfile = oci_fetch_array($qProfile)) {
$ips = array_map('trim', explode(',', $dProfile['ALLOWED_IP_ADDRESS']));
$allowedIP = array_merge($allowedIP, $ips);
}
Now you have one flat list of IPs which in_array
can search through.
However, since you're pulling those IPs from a database in the first place, you should probably do a simple database query instead of building and searching through this array in PHP.
in_array will check the value of the array, in your case it have multiple IP addresses in string format in array values.
Change
while($dProfile = oci_fetch_array($qProfile))
{
$allowedIP[] = array($dProfile['ALLOWED_IP_ADDRESS']);
}
To
$allowedIP = array();
while($dProfile = oci_fetch_array($qProfile))
{
$allowedIP = array_merge($allowedIP, array_map('trim', explode(',', $dProfile['ALLOWED_IP_ADDRESS'])));
}
You should use this code:
while($dProfile = oci_fetch_array($qProfile))
{
$allowedIps = explode(', ', $dProfile['ALLOWED_IP_ADDRESS']);
foreach($allowedIps as $singleAllowedIp)
{
$allowedIP[] = $singleAllowedIp;
}
}
Instead of
while($dProfile = oci_fetch_array($qProfile)) { $allowedIP[] = array($dProfile['ALLOWED_IP_ADDRESS']); }
test this code:
while($dProfile = oci_fetch_array($qProfile))
{
$allowedIP[] = array($dProfile['ALLOWED_IP_ADDRESS']);
}
if([[$_SERVER['REMOTE_ADDR']]]==$allowedIP)
{
$ip = 1;
}
else
{
$ip = 0;
}
echo $ip;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.