I have a text file : ban.txt have content
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";}
I write a script to find and ban IP in this txt
<?php
$banlist = file("ban.txt");
foreach($banlist as $ips ) {
开发者_如何学Pythonif($_SERVER["REMOTE_ADDR"] == $ips) {
die("Your IP is banned!");
}
}
?>
Can help me to list IP in this content, i m a newbie php. Thanks very much
Look this is an acknowledged crap solution based on an unclear question
Regex never seems a great solution, but I don't have a lot of detail on how consistent the file is.
1. Isolate "s" segments in your ban.txt
As such, and my regex isn't fantastic, but this regex should match the "s" segments which appear to be for IP bans (although your comment stating "The IP always in "ip"" confuses this a little).
Regex: s:[0-9]+:"[ ]*[0-9]+.[0-9]+.[0-9]+.[0-9]+";
2. Isolate the IPs within each "s" segment
Once we have these segments, we can strip the start bit up to the actual IP (i.e. turn s:123:"192.168.0.0";
into 192.168.0.0";
), and afterwards trim the end quotation mark and semi-colon (i.e. 192.168.0.0";
to 192.168.0.0
):
Regex for start junk (still need to trim end): s:[0-9]+:"[ ]*
Regex for end junk: [";]+
3. Example Code
This would give us this PHP code:
$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 */
Example: http://codepad.viper-7.com/S9rTQe
精彩评论