我已经建立了一个PHP IP黑名单系统,它的工作真的很好。现在,我希望它能够从txt文件中获取一个原因。
ip_blacklist.txt
1.2.4.5 , No Spamming Allowed
1.2.4.5 , No Spamming Allowed
1.2.4.5 , No Spamming Allowed现在,在PHP中,它得到了IP来将其与正在使用的用户IP进行比较,这是非常完美的。但是,如果IP与txt中的IP匹配,它将将您重定向到黑名单页面。我要它显示他们被列入黑名单的原因。
如何使用PHP获得与txt文件中的IP匹配的原因,然后将其链接到$reason?
发布于 2014-01-17 15:09:03
和上面的答案一样,我同意解决这个问题的最好方法是将用户的IP存储在数据库中,但是如果您仍然需要为它读取一个文件,那么这段代码应该完成以下工作:
<?php
//The file you will read
$file = fopen("ip_blacklist.txt", "r") or exit("Unable to open file!");
//Where we will store each ip as we read it
$ip = "";
$parts;
while(!feof($file))
{
//Split the line and save the parts
$parts = explode(" , ", fgets($file));
$ip = $parts[0];
$reason = $parts[1];
//And here you can compare it to the client's ip
//The first one is the ip read from the file
echo $ip."<br>";
//And this is how you would get the client's ip
echo $_SERVER['REMOTE_ADDR']."<br>";
}
//Close the file
fclose($file);
?>请注意,我使用的获取客户端IP的方法无论如何都不是最好的方法(因为它非常容易被欺骗)。有关这方面的更多信息,请在此处阅读How to get Client IP address in PHP?
-编辑-
我只是注意到你只是想检查一下IP,比较一下,找出原因。在这种情况下,将时间更改为:
while(!feof($file))
{
//Split the line and save the parts
$parts = explode(" , ", fgets($file));
$ip = $parts[0];
if($_SERVER['REMOTE_ADDR'] == $ip)
echo $parts[1];
}发布于 2014-01-17 14:59:24
编辑:编辑,以包括从文件中获取结果的preg_match方法,而不是db。该方法将检查用户是否在黑名单中,并得到用户的原因。
您可以简单地将用户IP存储在数据库中,并说明原因。然后在运行检查时,如果用户在黑名单中,查询数据库中的ip,并返回并显示原因。
$ip = $_SERVER['REMOTE_ADDR'];
$sql = 'SELECT reason FROM blacklist WHERE ip = "' . $ip . '"';然后对数据库运行该sql。当然,这是一个粗略的想法,没有针对sql注入的保护,所以在运行查询之前,我建议您使用某种形式的excaping并验证$ip是否为ip地址的正确格式。
总的进程将是:
如果您只是想通过文件来完成这一切,那么获取文件内容、查找ip和原因以及显示原因将是一个更好的方法。
这可以使用preg_match来完成。
$file = file_get_contents('path/to/blacklist/file');
$ip = $_SERVER['REMOTE_ADDR'];
$pattern = '#' . $ip . '\s,\s.*#';
if(preg_match($pattern, $file_contents, $matches)) {
$match = $matches[0];
$explode = explode(',', $match);
$reason = $explode[1];
echo $reason;
}注意,这是未经测试的,但我认为它会起作用。
https://stackoverflow.com/questions/21188715
复制相似问题