Skip to content

Instantly share code, notes, and snippets.

@ahmedash95
Last active July 12, 2020 09:35
Show Gist options
  • Save ahmedash95/fb2f38bdc24e37cd223d561b3fd53275 to your computer and use it in GitHub Desktop.
Save ahmedash95/fb2f38bdc24e37cd223d561b3fd53275 to your computer and use it in GitHub Desktop.
Github visitors counter
<?php
function createImage($content)
{
$font1 = 5;
$width1 = imagefontwidth($font1) * strlen($content);
$img_w = 240;
$img_h = 64;
$image = imagecreatetruecolor($img_w, $img_h);
$white = imagecolorallocate($image, 255, 255, 255);
$black = imagecolorallocate($image, 0, 0, 0);
imagefill($image, 0, 0, $white);
imagestring($image, 12, ($img_w / 2) - ($width1 / 2), 20, $content, $black);
imagepng($image);
imagedestroy($image);
}
//$db = new \PDO('sqlite:'.__DIR__.'/db.sqlite');
$db = new \SQLite3(__DIR__.'/db.sqlite');
$db->query('CREATE TABLE IF NOT EXISTS "visits" (
"id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
"referrer" TEXT,
"time" DATETIME
)');
$statement = $db->prepare('INSERT INTO "visits" ("referrer", "time") VALUES (:url, :time)');
$statement->bindValue(':url', $_SERVER['HTTP_REFERER'] ?? null);
$statement->bindValue(':time', date('Y-m-d H:i:s'));
$statement->execute();
$result = $db->prepare('SELECT count(*) FROM "visits"')->execute();
$count = $result->fetchArray()[0];
header("Content-type: image/png");
createImage($count);
@hossammohammed72
Copy link

You can I guess make the referer field unique and add a visits count attribute to the table then make the insert query on duplicate update that updates the visits count so now you can track most frequent referee and count them and also count refers numbers easily. Also you can add ip address to the table and track ips and unique ip visit, won't be so accurate because most users have dynamic ips but can be good as a start

@ahmedash95
Copy link
Author

Nice suggestions. feel free to make a PR https://github.com/ahmedash95/github-views

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment