Visitor Counter as Image

PHP

With this snippet you can generate an png image as a response, that counts every hit.

<?php

/***********
 *  Functions
***********/

function hex2rbg($hex){
    return [hexdec(substr($hex,0,2)),hexdec(substr($hex,2,2)),hexdec(substr($hex,4,2))];
}

function getCounter() {
    $c = file_get_contents('counter.txt');
    $c++;
    file_put_contents('counter.txt',$c);
    return $c;
}

/***********
 *  CONFIG
***********/

$config = [
    'width' => 200,
    'height' => 80,
    'stringfont' => 5,
    'stringpos' => [10,50],
    'background' => hex2rbg('333333'),
    'color' => hex2rbg('ffffff'),
    'font' => './BebasNeue-Regular.ttf',
    'fontsize' => 32,
    'fontangle' => 0,
];

// Create Image
$img = imagecreate($config['width'],$config['height']);

// Allocate Colors
$background = imagecolorallocate($img, $config['background'][0], $config['background'][1], $config['background'][2]);
$textcolor = imagecolorallocate($img, $config['color'][0], $config['color'][1], $config['color'][2]);

// Create Font
$font = imageloadfont($config['font']);

// Generate Text
$text = getCounter();

// Print Text
imagettftext ( $img , $config['fontsize'], $config['fontangle'] , $config['stringpos'][0],$config['stringpos'][1] , $textcolor , $config['font'] , $text);

// Generate Output
header( "Content-type: image/png" );
imagepng( $img );

// Deallocate colors
imagecolordeallocate($textcolor);
imagecolordeallocate($background);

// Destroy Image
imagedestroy( $img );

?>