Reputation: 2897
Is there a way to match a part of a string within an array in PHP?
I would like to validate a user ip against allowed IPs. Therefore I have created an array with IPs and coresponding partner_id. This works, however I also want to allow an entire subnet and would therefore need to mach against part of the array. Is this possible?
This is my code:
# define partner IPs
$partner_ips = array(
'192.168.56.1' => 0, // dev
'192.168.57.*' => 1 // office ips
);
# test for partner IP and associate partner_id if found
if (array_key_exists($_SERVER['REMOTE_ADDR'], $partner_ips))
$partner_id = $partner_ips[$_SERVER['REMOTE_ADDR']];
else
$partner_id = false;
Thank you for any help on this.
Upvotes: 0
Views: 89
Reputation: 89547
Check the ip format first. Build two different arrays, one for full ip adresses and one for subnets. An example class (feel free to make it PSR-2 compliant, since you use PHP 5.6 you can also declare the two arrays as class constants instead of static variables):
class RemoteAddress {
private $ip;
private $id;
private static $partners_ips = [
'192.168.56.1' => 0,
'192.168.58.4' => 2,
'192.168.59.2' => 3 ];
private static $partners_subnets = [ // note that subnets must end with a dot
'192.168.57.' => 1,
'192.168.60.' => 4,
'192.168.61.' => 5 ];
public function __construct($ip) {
if (filter_var($ip, FILTER_VALIDATE_IP) === false)
throw new Exception("invalid IP address");
$this->ip = $ip;
$this->id = $this->searchID();
}
public function getIDPartner() {
return $this->id;
}
private function searchID() {
if (array_key_exists($this->ip, self::$partners_ips))
return self::$partners_ips[$this->ip];
foreach (self::$partners_subnets as $subnet => $id) {
if (strpos($this->ip, $subnet) === 0)
return $id;
}
return false;
}
}
You can use it like this:
try {
if (isset($_SERVER['REMOTE_ADDR'])) {
$remAddr = new RemoteAddress($_SERVER['REMOTE_ADDR']);
var_dump($remAddr->getIDPartner());
} else throw new Exception('$_SERVER[\'REMOTE_ADDR\'] is not defined');
} catch(Exception $e) {
echo $e->getMessage();
}
Upvotes: 1
Reputation: 55
You can use in_array for check if your string exist in array or not
http://php.net/manual/en/function.in-array.php
Upvotes: 0