note 89012 deleted from function.getenv by danbrown

From: Date: Mon, 23 Feb 2009 01:05:42 +0000
Subject: note 89012 deleted from function.getenv by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-150994@lists.php.net to get a copy of this message
Note Submitter: estarapapax at gmail dot com ---- This is a sample function for checking if your visitor comes from this certain country. This is especially useful for amateur webmasters. Sample use of function: <?php if(check_coutry('http://www.example.com/subdomain/philippines.csv') === true) echo 'You are from the Philippines'; ?> Basically, you'll need CSV (or TXT) which lists the IP ranges of a certain country. Example (excerpt of the philippines.csv only): 58.69.0.0, 58.69.255.255 58.71.0.0, 58.71.127.255 61.9.0.0, 61.9.127.255 61.14.28.0, 61.14.28.63 61.14.41.136, 61.14.41.143 and so on until the end You may obtain these CSV files in a number of websites out there. Be sure to update these CSV files regularly as these IP ranges change from time to time. Here is the function: <?php function check_country($url_csv){ $curl_handle = curl_init(); curl_setopt($curl_handle, CURLOPT_URL, $url_csv); curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1); $str_fromfile = curl_exec($curl_handle); curl_close($curl_handle); $line = explode("\n", $str_fromfile); $ip = getenv(REMOTE_ADDR); //gets the IP of the visitor $ipd = explode('.', $ip); $ipnum = (16777216 * (int) $ipd[0]) + (65536 * (int) $ipd[1]) + (256 * (int) $ipd[2]) + ((int) $ipd[3]); //IP number of visitor for($i = 0; $line[$i] != NULL && $is_positive == NULL; $i++){ // the condition $line[$i] != NULL means that you should not put blank lines before the end of your CSV. The values should start at line 1. $line[$i] = rtrim(ltrim($line[$i])); //you may remove this if you are sure the csv doesnt contain whitespaces $ends = explode(',',$line[$i]); //for CSV (comma-separated values), comma is the separator. You may change this if your TXT uses different separator. $ends1 = explode('.', $ends[0]); $ends2 = explode('.', $ends[1]); $ends1 = rtrim($ends1); //again, you may remove this if there are no whitespaces in your CSV $ends2 = ltrim($ends2); //yet, again $start = (16777216 * (int) $ends1[0]) + (65536 * (int) $ends1[1]) + (256 * (int) $ends1[2]) + ((int) $ends1[3]); //Start IP number $stop = (16777216 * (int) $ends2[0]) + (65536 * (int) $ends2[1]) + (256 * (int) $ends2[2]) + ((int) $ends2[3]); //End IP number if($ipnum >= $start && $ipnum <= $stop){ $is_positive = 1; } //If visitor's IP number is between the start and end } //Loops to the next range if($is_positive == 1) return true; else return false; } ?>

« previous php.notes (#150994) next »