01 | <?php |
02 | $ip = $_SERVER [ 'REMOTE_ADDR' ]; |
03 | geoCheckIP( $ip ); |
04 | |
05 | // print_r(geoCheckIP($ip)); |
06 | //Array ( [domain] => dslb-094-219-040-096.pools.arcor-ip.net [country] => DE - Germany [state] => Hessen [town] => Erzhausen ) |
07 | |
08 | //Get an array with geoip-infodata |
09 | function geoCheckIP( $ip ) |
10 | { |
11 | //check, if the provided ip is valid |
12 | if (!filter_var( $ip , FILTER_VALIDATE_IP)) |
13 | { |
14 | throw new InvalidArgumentException( "IP is not valid" ); |
15 | } |
16 | |
17 | //contact ip-server |
18 | $response =@ file_get_contents ( 'http://www.netip.de/search?query=' . $ip ); |
19 | if ( empty ( $response )) |
20 | { |
21 | throw new InvalidArgumentException( "Error contacting Geo-IP-Server" ); |
22 | } |
23 | |
24 | //Array containing all regex-patterns necessary to extract ip-geoinfo from page |
25 | $patterns = array (); |
26 | $patterns [ "domain" ] = '#Domain: (.*?) #i' ; |
27 | $patterns [ "country" ] = '#Country: (.*?) #i' ; |
28 | $patterns [ "state" ] = '#State/Region: (.*?)<br#i' ; |
29 | $patterns [ "town" ] = '#City: (.*?)<br#i' ; |
30 | |
31 | //Array where results will be stored |
32 | $ipInfo = array (); |
33 | |
34 | //check response from ipserver for above patterns |
35 | foreach ( $patterns as $key => $pattern ) |
36 | { |
37 | //store the result in array |
38 | $ipInfo [ $key ] = preg_match( $pattern , $response , $value ) && ! empty ( $value [1]) ? $value [1] : 'not found' ; |
39 | } |
40 | |
41 | return $ipInfo ; |
42 | } |
43 | |
44 | ?> |
45 | |