ionicle Posted June 17, 2013 Share Posted June 17, 2013 (edited) Hey there, php freaks. I'm trying to whip up a script that is supposed to do the following: I have a list of certain IP address ranges and single IP addresses that I would like to use as an array in a separate file. Whenever someone visits the webpage, I want, depending on whether the visitor's IP address matches any of the IP ranges/IPs in the array, one of two actions to be executed: 1. Visitor's IP address is not found on the IP list - show a certain html code ( page variation 1 ) 2. Visitor's IP address matches one of the entries on the list - show another html code ( page variation 2 ). How would I go about doing that? Do I have to use "ip2long" for the IP ranges? Also, since my IP list will include both single IP addresses and IP ranges, how should I go about checking for both? <?php$start_range = ip2long( "x.x.x.x" );$end_range = ip2long( "x.x.x.x" );$user_ip = ip2long( $_SERVER['REMOTE_ADDR'] );if ( $user_ip >= $start_range && $user_ip <= $end_range) { /* html code */}?> That should do the trick, but I want to define the database with the IP ranges in a separate file, not directly in the php code, since there are quite a few of them. The database with the IP ranges should be a simple TXT file, not a SQL db. Edited June 17, 2013 by ionicle Quote Link to comment Share on other sites More sharing options...
DavidAM Posted June 17, 2013 Share Posted June 17, 2013 If you are using a database at all, I would definitely put this in a table in the DB. If you are not using a database, I would consider using one for this. In any case I would recommend that all "single" IP addresses be stored as a range -- the start and end of the range is the same value. This way you have one "table" (or file) with a consistent record structure. With a database you could then do: SELECT COUNT(*) FROM IPTable WHERE 'visitorsIP' BETWEEN startIP AND endIPYou should get a result of zero or one -- one meaning they are in the list. You can use ip2long() if you want, but unless there are going to be a large number of them, I'm not sure I would. If you use a file, follow a few simple "rules": 1. Always store all of the addresses as 15 characters -- use leading zeros: 010.002.123.003. 2. Use a standard delimiter between the two elements of the range: space or tab 3. Always sort the file after making changes. You are going to have to process each line in the file one at a time. If you have it sorted, then once you reach a range that is greater than the visitor's address, you can stop checking because all of the remaining entries are also greater. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.