查找IP在TXT内容php


find ip in txt content php

我有一个文本文件:ban.txt

a:5:{i:14528;s:15:" 118.71.102.176";i:6048;s:15:" 113.22.109.137";i:16731;s:3:"  118.71.102.76";i:2269;s:12:" 1.52.251.63";i:9050;s:14:"123.21.100.174";}

我写了一个脚本来查找和禁止这个文本中的IP

<?php
$banlist = file("ban.txt");
foreach($banlist as $ips ) {
    if($_SERVER["REMOTE_ADDR"] == $ips) {
        die("Your IP is banned!");
    }
}
?>

可以帮助我在这个内容中列出IP,我是一个新手php。非常感谢

这是基于一个不清楚的问题的公认的垃圾解决方案

Regex似乎从来都不是一个很好的解决方案,但我没有很多关于文件一致性的细节。

1。在ban.txt

中分离"s"段

因此,我的正则表达式不是很好,但这个正则表达式应该匹配"s"段,这似乎是IP禁令(尽管你的评论说"IP总是在"IP"中"混淆了这一点)。

Regex: s:[0-9]+:"[ ]*[0-9]+.[0-9]+.[0-9]+.[0-9]+";

2。隔离每个"s"段内的ip

一旦我们有了这些段,我们可以剥离起始位到实际IP(即将s:123:"192.168.0.0";变成192.168.0.0";),然后修剪结束引号和分号(即192.168.0.0";192.168.0.0):

Regex for start junk (still need to trim end): s:[0-9]+:"[ ]*
Regex for end junk: [";]+

3。示例代码

这将给我们这样的PHP代码:
$banText = file_get_contents("ban.txt"); 
/* Evil, evil regexes */
$sSegmentsRegex = '/s:[0-9]+:"[ ]*[0-9]+.[0-9]+.[0-9]+.[0-9]+"/';
$removeStartJunkRegex = '/s:[0-9]+:"[ ]*/';
$removeEndJunkRegex = '/[";]+/'; /* Could use rtrim on each if wanted */
$matches = array();
/* Find all 's' bits */
preg_match_all($sSegmentsRegex, $banText, $matches); 
$matches = $matches[0]; /* preg_match_all changes $matches to array of arrays */
/* Remove start junk of each 's' bit */
$matches = preg_replace($removeStartJunkRegex, "", $matches); 
$matches = preg_replace($removeEndJunkRegex, "", $matches); 
foreach($matches as $ip) {
    if($_SERVER["REMOTE_ADDR"] == $ip) {
        die("Your IP is banned!");
    }
 }
print_r($matches); /* Shows the list of IP bans, remove this in your app */

示例:http://codepad.viper - 7. - com/s9rtqe