|
| Дата |
|
USD/RUB | 93.4409 | BTC/USD | 64753.7549 |
|
|
|
Скрипты, программы и технические решения Обсуждаем скрипты, программы и новые технологии. |
20.09.2010, 10:55
|
#1
|
Senior Member
Регистрация: 27.02.2009
Сообщений: 144
Бабло: $5800
|
Как добавить geoip базу?
Подскажите как добавить lite версию geoip базы в скрипт Simple TDS v1.1beta?
Вот файл функции, подскажите пожалуйста решения, а то, я уже 3й день не могу сделать
Код:
<?php
function ip2c($ip) {
$ip_number = sprintf("%u", ip2long($ip));
// Query for getting visitor countrycode
$country_query = "SELECT country_code2,country_name FROM iptoc ".
"WHERE IP_FROM<=$ip_number ".
"AND IP_TO>=$ip_number ";
// Executing above query
$country_exec = @mysql_query($country_query);
// Fetching the record set into an array
$ccode_array=@mysql_fetch_array($country_exec);
// getting the country code from the array
$country_code=$ccode_array['country_code2'];
// getting the country name from the array
$country_name=$ccode_array['country_name'];
// Display the Visitor coountry information
$ret[0] = $country_code;
$ret[1] = $country_name;
// Closing the database connection
return $ret;
}
function searchany ($haystack, $needle) {
global $debug;
if (substr($needle,0,1) != "*") $needle = "^".$needle;
if (substr($needle,-1) != "*") $needle = $needle."$";
$needle = str_replace("*", "(.*)", $needle);
$needle = str_replace("/", "\/", $needle);
if ($debug) echo $needle."<br>";
if (preg_match ("/$needle/i", $haystack)) {
$res=true;
} else {
$res=false;
}
return $res;
}
function gotoreserved() {
global $reserved_url, $debug, $getparams;
################# Добавляем GET параметры ######################
unset($params);
foreach ($getparams as $key=>$val) {
$params[] = urlencode($key)."=".urlencode($val);
}
if (@is_array($params)) {
$param_string = implode('&',$params);
if (stristr($reserved_url, '?')) $param_string = "&".$param_string; else $param_string = "?".$param_string;
} else {
$param_string = '';
}
$reserved_url = $reserved_url.$param_string;
################################################################
if ($debug) {
echo "Here redirect to RESERVED URL <b>$reserved_url</b><br>";
} else {
header("Referer: ".@$_SERVER['HTTP_REFERER']);
header("Location: $reserved_url");
}
}
function gg($v) {
return $_GET[$v];
}
function pp($v) {
return $_POST[$v];
}
function rr($v) {
return $_REQUEST[$v];
}
class tds
{
var $schems = Array();
var $outs = Array();
var $out2s = Array();
var $filters = Array();
var $filt2o = Array();
var $stats = Array();
var $tables = Array(); //Названия всех таблиц
var $ai_tables = Array("tds_schems","tds_outs","tds_filters"); //Таблицы с автоинкрементом
var $db = array();
function tds () {
$d = opendir ("data");
while ($file = readdir ($d))
{
if (stristr($file,'.dat'))
{
$tablename = str_replace('.dat','',$file);
$this->tables[] = $tablename;
$ff = fopen("data/$file","r");
$buf="";
while (!feof($ff)) {
$buf .= fgets($ff);
}
$this->db[$tablename] = unserialize($buf);
}
}
closedir ($d);
}
function select_all($table) {
$data = $this->db[$table];
unset($data['autoinc']);
return $data;
}
function select_where($table, $wheres) {
$data = $this->db[$table];
$ret_data = array();
foreach ($wheres AS $key=>$val) {
foreach ($data as $line) {
if (isset($line[$key])) {
if ($line[$key] == $val) $ret_data[] = $line;
}
}
}
return $ret_data;
}
function insert($table,$date) {
// $data = $this->db[$table];
$ai = $this->db[$table]['autoinc'];
if (!(array_search($table,$this->ai_tables) === false)) {
$date['id'] = $ai;
$insert_id = $ai;
$this->db[$table][] = $date;
$ai++;
$this->db[$table]['autoinc'] = $ai;
$this->save_tables($table);
return $insert_id;
} else {
$this->db[$table][] = $date;
$this->save_tables($table);
return 0;
}
}
function update_where($table,$date,$wheres) {
$data = $this->db[$table];
foreach ($wheres AS $key=>$val) {
foreach ($data as $kk=>$line) {
if (isset($line[$key])) {
if ($line[$key] == $val) {
foreach ($date AS $kkey=>$vval) {
$this->db[$table][$kk][$kkey] = $vval;
}
}
}
}
}
$this->save_tables($table);
}
function delete_where($table,$wheres) {
$data = $this->db[$table];
foreach ($wheres AS $key=>$val) {
foreach ($data as $kk=>$line) {
if (isset($line[$key])) {
if ($line[$key] == $val) unset($this->db[$table][$kk]);
}
}
}
$this->save_tables($table);
}
function save_tables($table = "all") {
if ($table=="all") {
$alltables = $this->tables;
} else {
$alltables[] = $table;
}
foreach ($alltables AS $tablename) {
$full_ser = serialize($this->db[$tablename]);
$fd = fopen("data/$table.dat", "w+");
fputs($fd,$full_ser);
fclose($fd);
}
}
}
class stats
{
var $ip; //IP-адрес серфера
var $ip_number;
var $cc; //Country Code серфера
var $cn; //Country Name серфера
var $getparams;
var $ua;
var $ref; //HTTP_REFERER запроса
var $st_days; //Названия всех файлов с данными по дням. (без разширения .dat)
var $all_stats; //База данных статистики по всем имеющимся дням
var $today; //Сегодняшний штамп в формате ГГГГММДД
var $delday; //Штамп дня удаления
function stats() {
global $debug;
$this->ip = $_SERVER['REMOTE_ADDR']; //IP-адрес серфера
if ($debug) $this->ip = "210.65.34.86"; // !!! TEST TW (TAIWAN) IP-Address !!!
$this->ip_number = sprintf("%u", ip2long($this->ip));
#$codes = ip2c($this->ip);
$this->cc = @$_SERVER["GEOIP_COUNTRY_CODE"]; //Country Code серфера
$this->cn = @$_SERVER["GEOIP_COUNTRY_NAME"]; //Country Name серфера
if ($debug) $this->cc = "TW"; // !!! TEST TW !!!
if ($debug) $this->cn = "Taiwan"; // !!! TEST TAIWAN !!!
$this->getparams = $_GET;
unset($this->getparams['sid'],$this->getparams['sname']);
$this->ua = @$_SERVER['HTTP_USER_AGENT'];
$this->ref = @$_SERVER['HTTP_REFERER']; //HTTP_REFERER запроса
if ($debug) $this->ref = "http//www.fff.com?sdsd=sdfsd&df=1&tt=%F3%4D"; // !!! TEST !!!
$d = opendir ("data/stats");
while ($file = readdir ($d))
{
if (stristr($file,'.dat'))
{
$st_day = str_replace('.dat','',$file);
$this->st_days[] = $st_day;
}
}
closedir ($d);
$ts = time();
$delts = $ts - 60*60*24*10;
$this->today = date('Ymd', $ts);
$this->delday = date('Ymd', $delts);
if ((@array_search($this->today,$this->st_days)) === false) {
$ff = fopen("data/stats/$this->today.dat","w+");
$dat = array();
fputs($ff,serialize($dat));
fclose($ff);
$this->st_days[] = $this->today;
}
foreach($this->st_days AS $kk=>$st_day) {
if ($st_day <= $this->delday) {
unset($this->st_days[$kk]);
unlink("data/stats/$st_day.dat");
continue;
}
}
}
function getstats($day_stamp = "all") {
if ($day_stamp == "all") {
$stamps = $this->st_days;
} else {
$stamps = array($day_stamp);
}
foreach ($stamps AS $stamp) {
$ff = fopen("data/stats/$stamp.dat","r");
$buf="";
while (!feof($ff)) {
$buf .= fgets($ff);
}
$ret[$stamp] = unserialize($buf);
fclose($ff);
}
return $ret;
}
function update($out_num){
$today_stats = $this->getstats($this->today);
$ts = time();
$dttm = date('Y-m-d H:i:s', $ts);
$curr_stats['dt'] = $dttm;
$curr_stats['country'] = $this->cn;
$curr_stats['ip'] = $this->ip;
$curr_stats['ref'] = $this->ref;
$curr_stats['ua'] = $this->ua;
$curr_stats['oid'] = $out_num;
$today_stats[$this->today][] = $curr_stats;
$ff = fopen("data/stats/$this->today.dat","w+");
fputs($ff,serialize($today_stats[$this->today]));
fclose($ff);
}
}
?>
gl
|
|
|
21.09.2010, 09:31
|
#2
|
Senior Member
Регистрация: 18.08.2010
Сообщений: 360
Бабло: $66120
|
судя по функции ip2c($ip), табличка должна выглядеть как то так:
Код:
CREATE TABLE 'iptoc' (
'IP_TO' int(4) unsigned NOT NULL,
'IP_FROM' int(4) unsigned NOT NULL,
'country_code2' char(2) NOT NULL,
'country_name' text,
PRIMARY KEY ('IP_TO'),
KEY 'bip_index' ('IP_TO'),
KEY 'eip_index' ('IP_FROM')
) ENGINE=MyISAM DEFAULT CHARSET=latin1
в файле от сюда http://geolite.maxmind.com/download/...CountryCSV.zip
3-я колонка - IP_TO
4-я колонка - IP_FROM
5-я колонка - country_code2
6-я колонка - country_name
Делаешь дамп в котором куча запросов с инсертами, что то типа:
Код:
INSERT DELAYED INTO iptoc (IP_TO,IP_FROM,country_code2,country_name) VALUES (16777216,17301503,"AU","Australia");
Если что позже могу скинуть готовый дамп
ps: а вообще определение через их бинарный файл, работает быстрее.
|
|
|
21.09.2010, 10:41
|
#3
|
автоматизирую интернеты
Регистрация: 05.07.2009
Адрес: chesser.ru
Сообщений: 3,362
Бабло: $470735
|
вариант с БД не самый лучший, тем более для тдс
лучше PHP PECL extension, ну или аналоги
|
|
|
21.09.2010, 10:45
|
#4
|
$400
Регистрация: 17.05.2009
Сообщений: 13,949
Бабло: $1895460
|
база несколько метров весит
серверный траф сжирать будет и тормозить будет
|
|
|
21.09.2010, 11:42
|
#5
|
Senior Member
Регистрация: 06.06.2007
Сообщений: 311
Бабло: $36103
|
Simple TDS v1.1beta не работает с БД
|
|
|
21.09.2010, 11:49
|
#6
|
Senior Member
Регистрация: 18.08.2010
Сообщений: 360
Бабло: $66120
|
Цитата:
Сообщение от k3t
Подскажите как добавить lite версию geoip базы в скрипт Simple TDS v1.1beta?
|
аа, наверное вот эти надо понять как, "Simple TDS v1.1beta не работает с базой, подскажите как мне побойтись без базы?" Ну пиздец..
|
|
|
|