Okay, I've spent half the day cleaning up all of my scripts and changing the order in which they are called to reduce server overhead as much as possible. I don't think this script was a problem per say but that it was the last straw on the camel's back. I'm currently running on a cleaned up version of the function that does a binary compare without reading the file into memory. I seemed to get the best overall results with it. If anyone has suggestions as to ways I could further clean up this script I'd appreciate feedback.
Here's the latest version of it:
Code:
function ipcountrycode($ip){
$ip=ip2long($ip);
$low = 130;
// Open the csv file for reading
$csvfilename="ip2country.csv";
$fp = fopen($csvfilename, "r");
fseek($fp, 75000, SEEK_END);
$high = ftell($fp);
while ($low <= $high) {
$mid = floor(($low + $high) / 2); // C floors for you
//Seek to half way through
fseek($fp, $mid);
// Moves to proper line
//if($mid != 0){
$line=fgets($fp);
//}
// Read line
$line=fgets($fp);
$line = str_replace("\"", "",$line);
$ipdata = explode(",",$line);
if ($ip >=$ipdata[0] && $ip<=$ipdata[1]){
$low=$high+1;
}
elseif($ip >=$ipdata[0]){
$low = $mid + 1;
}
else {
$high = $mid - 1;
}
}
fclose($fp);
$line="";
return $ipdata[4];
}
Bookmarks