gpt4 book ai didi

php - 使用范围的 IP 白名单

转载 作者:行者123 更新时间:2023-11-29 15:43:20 28 4
gpt4 key购买 nike

我为我的服务用户提供了一个选项,仅允许从他们可以添加的特定 IP 地址访问他们的帐户。检查的工作原理如下:

$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
exit;
}

$whitelist = array();
$sql = "SELECT IP_Address FROM IPWhitelist WHERE owner=$userid";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$whitelist[] = $row["IP_Address"];
}

if (in_array($_SERVER['REMOTE_ADDR'], $whitelist)) {
//Action for allowed IP Addresses
} else {
//Action for all other IP Addresses
echo '<html>This account has enabled IP Whitelisting and has rejected your connection.<br /><br />If you believe this to be an error, please email hello@xxxxxx';
echo "<br /><br />IP Address: ".$_SERVER['REMOTE_ADDR']."</html>";
exit;
}
}
$conn->close();

上面的代码可以很好地检查特定的 IP 地址,但是我该如何允许用户指定 IP 范围呢?所以,167.22.*

最佳答案

如果您要使用 CIDR notation,则不要使用通配符,例如 167.22.*那么你可能会采用这样的方法 - 主要使用 PHP 而不是复杂的 sql 查询。以下内容不考虑 IPv6 地址。

<?php

function createIPRange( $cidr ){
$a = explode( '/', $cidr );
$x = 32 - $a[1];
$c = pow( 2, $x );
$s = ip2long( $a[0] );
$e = $s + $c;
$r = array_map( 'long2ip', range( $s, $e ) );
/* remove last 2 entries from generated list */
array_pop( $r );
array_pop( $r );
/* return ip addresses */
return $r;
}

$cidr='167.22.0.0/16'; // 65,535 addresses
$ip=$_SERVER['REMOTE_ADDR'];
$email='hello@xxx.yyy';

$whitelist=array();
$ranges=array();




$sql='select `ip_address` from `ipwhitelist` where `owner`=?';
$stmt=$conn->prepare( $sql );
$stmt->bind_param( 's', $userid );
$stmt->execute();

$res=$stmt->get_result();
while( $rs=$res->fetch_object() ){
if( strstr( $rs->ip_address, '/' ) )$ranges[]=$rs->ip_address;
else $whitelist[]=$rs->ip_address;
}

/* create the ip addresses for each cidr range */
foreach( $ranges as $cidr ){
$whitelist[]=createIPRange( $cidr );
}


/* test to see if the ip is allowed */
if( in_array( $ip, $whitelist ) ){
/* OK */
http_response_code( 200 );
} else {

/* Bogus */
$message=sprintf('
This account has enabled "IP Whitelisting" and has rejected your connection.
<br /><br />
If you believe this to be an error, please email %s
<br /><br />
IP Address: %s',
$email,
$ip
);


printf('
<html>
<head>
<title>Forbidden</title>
</head>
<body>
%s
</body>
</html>', $message );


http_response_code( 403 );
}

关于php - 使用范围的 IP 白名单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57344925/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com