0) { $fileok = FALSE; break 2; } break; } } fclose($ipdbf); fclose($ipdbcf); // Remove the temp file. If the data is ok, move // it to the destination, or else delete that too unlink($ipdbt); if (file_exists($ipdbc)) { if (!$fileok) { unlink($ipdbc); } else { rename($ipdbc, $ipdb); create_ip_to_country_index($ipdb, $ipidx, $indexby); } } } // Create local index for ip-to-country.com data function create_ip_to_country_index($ipdb, $ipidx, $indexby) { // Last indexed number and last record number $lastidx = $recnum = 0; // We store the index in a PHP array temporarily $idx_list = [$indexby, "0,0"]; // Open database for reading $ipdbf = fopen($ipdb, "r"); // Return with error in case of we cannot open the db if (!$ipdbf) { die("Unable to open '$ipdb' for reading"); } // While we can read the file while (!feof($ipdbf)) { // Get one record $record = fread($ipdbf, 24); // Unable to read a record and not at end => error if (strlen($record) != 24 && !feof($ipdbf)) { die("Incorrect ip-to-country database format"); } // This is a new record $recnum++; // Get the start of the range for this record $range_start = (float) substr($record, 0, 10); // If this range starts a new step with our granularity, // add a new element to the index array if (intval($range_start / $indexby) > $lastidx) { $lastidx = intval($range_start / $indexby); $idx_list[] = "$lastidx,$recnum"; } } // Close the database file fclose($ipdbf); // Write out index to file $ipidxf = fopen($ipidx, "w"); if (!$ipidxf) { die("Unable to open '$ipidx' for writing"); } fwrite($ipidxf, join("\n", $idx_list)); fclose($ipidxf); }