Home
Valruin's Friends
 
[Most Recent Entries] [Calendar View] [Friends View]

Below are the most recent 1 friends' journal entries.

    Sunday, December 27th, 2009
    milambar
    6:20a
    Php woes, and perhaps a solution for others.
    So, I recently had to write a small script in php that allowed me to block ip's or ip ranges listed in a text file.

    There are a number of solutions for this scattered about the web, but I didn't like any of the implementations. Some were buggy, others didn't do exactly what I wanted, and the remainder didn't fit into my coding style. Plus, I like to write my own code, it avoids licencing issues.

    Hers the code I came up with.

    <?php	
    	function isBanned($ip) {
    		$bannedFile=("bannedIps.dat");
    		$fh = fopen($bannedFile, "r");
    		if (!$fh) {
    			return true;
    		} else {
    			while ($line = fgets($fh)) {
    				if (ipMatch($line, $ip)) {
    					fclose($fh);
    					return true;
    				}
    			}
    			fclose($fh);
    			return false;
    		}
    	}
    	
    	function ipMatch($thisIp, $ip) {
    		$needle = strpos($thisIp, "*", 0);
    		if ($needle !== false) {
    			$thisIp = substr($thisIp, 0, ($needle-1));
    		}
    		$haystack = $ip;
    		$needle = $thisIp;
    		rtrim($haystack);
    		$needle=preg_replace("/\s*/", "", $needle);
    		if (preg_match("/^$needle/", $haystack)) {
    			return true;
    		}
    		return false;
    	}
    ?>
    


    To use it, just save it as "ipban.php" or something similar, then include("ipban.php") in your main code, and then if (isBanned("$ip"))...
About LiveJournal.com

Advertisement