Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Standalone simple hit counter
<?php
// вызывается как standalone_counter.php?id=N
// по умолчанию (если id опущен) - принимается равным 1
function getRealIP() {
$ip = '127.0.0.1';
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
return $ip;
}
// local
$settings = array(
'hostname' => 'localhost',
'database' => 'test',
'username' => 'test',
'password' => 'password',
'table' => 'counter_hits',
'port' => 3306,
);
$dsl = "mysql:host={$settings['hostname']};port={$settings['port']};dbname={$settings['database']}";
// подключаемся к БД
try {
$dbh = new \PDO($dsl, $settings['username'], $settings['password']);
$dbh->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
$dbh->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_ASSOC);
} catch (\PDOException $e) {
die ("Unable to connect {$dsl}");
}
$id_banner = $_GET['id'] ?? 1;
// проверяем существование таблицы и если нет - создаем
$query_create_table = "CREATE TABLE IF NOT EXISTS `{$settings['table']}` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`id_banner` INT(11) DEFAULT NULL,
`alias_banner` CHAR(8) DEFAULT NULL,
`dayvisit` DATE DEFAULT NULL,
`ipv4` INT(10) UNSIGNED DEFAULT NULL,
`hits` INT(11) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `date+ipv4` (`dayvisit`,`ipv4`),
KEY `ipv4` (`ipv4`),
KEY `id_banner` (`id_banner`)
) ENGINE=MYISAM AUTO_INCREMENT=1 DEFAULT CHARSET=latin1";
// вставка баннера
$query = "INSERT INTO `{$settings['table']}` (id_banner, dayvisit, ipv4, hits) VALUES(:id_banner, CURDATE(), INET_ATON(:ipv4), 1)
ON DUPLICATE KEY UPDATE hits = hits+1";
$sth = $dbh->prepare($query);
try {
$sth->execute( array(
'ipv4' => getRealIP(),
'id_banner' => $id_banner
) );
} catch (\PDOException $e) {
echo $e->getMessage();
}
$dbh = null;
// рисуем прозрачную точку:
// https://stackoverflow.com/a/30664750/5127037
header('Content-Type: image/gif');
die("\x47\x49\x46\x38\x39\x61\x01\x00\x01\x00\x90\x00\x00\xff\x00\x00\x00\x00\x00\x21\xf9\x04\x05\x10\x00\x00\x00\x2c\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02\x04\x01\x00\x3b");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.