A simple, customizable hit counter using PHP, MySQL, and SVG. It tracks the number of hits on a specific URL and displays it in a visually appealing way. This project is designed to be easy to set up and integrate into any website.
Since the project https://github.com/gjbae1212/hit-counter is archived, I decided to create a my own self-hosted version.
Create the required table in your MySQL database:
CREATE TABLE hits (
url VARCHAR(255) UNIQUE,
hits INT DEFAULT 0
);
Update database credentials in your PHP script:
$host = 'localhost';
$db = 'hitcounter';
$user = 'username';
$pass = 'password';
Embed the counter on your site as follows:
<img src="https://yourdomain.com/hit_counter.php?url=https://example.com&page&count_bg=%2379C83D&title_bg=%23555555&title=π" alt="Hit Counter">
url
: Unique identifier for the counted page.count_bg
: Background color of the count (default:#79C83D
).title_bg
: Background color of the title area (default:#555555
).title
: Title icon or text (default:π
).
<?php
// Database connection
$host = 'localhost';
$db = 'hitcounter';
$user = 'username';
$pass = 'password';
$charset = 'utf8mb4';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
try {
$pdo = new PDO($dsn, $user, $pass, $options);
} catch (PDOException $e) {
exit('Database error: ' . $e->getMessage());
}
// Parameters
$url = $_GET['url'] ?? 'default';
$count_bg = $_GET['count_bg'] ?? '#79C83D';
$title_bg = $_GET['title_bg'] ?? '#555555';
$title = $_GET['title'] ?? 'π';
// Prevent caching
header('Content-Type: image/svg+xml');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
// Track hits
$stmt = $pdo->prepare("INSERT INTO hits (url, hits) VALUES (?, 1) ON DUPLICATE KEY UPDATE hits = hits + 1");
$stmt->execute([$url]);
// Retrieve current hit count
$stmt = $pdo->prepare("SELECT hits FROM hits WHERE url = ?");
$stmt->execute([$url]);
$count = $stmt->fetchColumn();
// Render SVG
echo <<<SVG
<svg xmlns="http://www.w3.org/2000/svg" width="120" height="25">
<rect width="40" height="25" fill="$title_bg" />
<rect x="40" width="80" height="25" fill="$count_bg" />
<text x="20" y="17" font-size="12" fill="#FFFFFF" font-family="Arial, sans-serif" text-anchor="middle">$title</text>
<text x="80" y="17" font-size="12" fill="#FFFFFF" font-family="Arial, sans-serif" text-anchor="middle">$count</text>
</svg>
SVG;
- Unique hit counting per URL
- Customizable appearance
- SVG-based, no caching