我使用 .txt 文件而不是数据库制作了一个简短的访客计数器脚本。统计信息通过图像生成器脚本输出。两个脚本都可以正常工作,但是当它们组合在一起时,访问者计数器的数字不是增加 1,而是每次页面浏览量增加 2。如果有人能花时间看看我做错了什么,将不胜感激。确实花了几个小时试图弄清楚但没有运气。
第一个文件 (page_counter.html)
<?php
include 'config.php';
/* -------------------------------------------------------------------------- */
// HEX TO RGB CONVERTER CODE
function hex2rgb($hex) {
$hex = str_replace("#", "", $hex);
if(strlen($hex) == 3) {
$r = hexdec(substr($hex,0,1).substr($hex,0,1));
$g = hexdec(substr($hex,1,1).substr($hex,1,1));
$b = hexdec(substr($hex,2,1).substr($hex,2,1));
} else {
$r = hexdec(substr($hex,0,2));
$g = hexdec(substr($hex,2,2));
$b = hexdec(substr($hex,4,2));
}
$rgb = array($r, $g, $b);
return $rgb;
}
//hit counter code
$counter = file_get_contents("count.txt");
$counter = trim($counter);
$counter += 1;
file_put_contents("count.txt", $counter);
//hex to rgb colour converter code
$bg_rbg = hex2rgb(BACKGROUND_COLOUR_HEX);
$txt_rbg = hex2rgb(TEXT_COLOUR_HEX);
$shadow_rbg = hex2rgb(SHADOW_COLOUR_HEX);
/* -------------------------------------------------------------------------- */
// IMAGE GENERACTOR CODE
header('Content-Type: image/png');
//Creates the background
$im = imagecreatetruecolor(IMAGE_WIDTH, IMAGE_HEIGHT);
//Creates the colours
$background = imagecolorallocate($im, $bg_rbg[0], $bg_rbg[1], $bg_rbg[2]);
$main_text_colour = imagecolorallocate($im, $txt_rbg[0], $txt_rbg[1], $txt_rbg[2]);
$shadow_colour = imagecolorallocate($im, $shadow_rbg[0], $shadow_rbg[1], $shadow_rbg[2]);
imagefilledrectangle($im, 0, 0, 500, 100, $background);
//Assigns a font path and font
$font = dirname(__FILE__). '/' . FONT_TYPE;
//Adds some shadow to the text
imagettftext($im, FONT_SIZE, 0, MAIN_X+1, MAIN_Y+1, $shadow_colour, $font, $counter);
//Creates the image
imagettftext($im, FONT_SIZE, 0, MAIN_X, MAIN_Y, $main_text_colour, $font, $counter);
//Using imagepng() results in clearer text compared with imagejpeg()
imagepng($im);
imagedestroy($im);
?>
第二个文件(config.php)
<?php
//Enter your desired background image width below
define('IMAGE_WIDTH', 90);
//Enter your desired background image height below
define('IMAGE_HEIGHT', 60);
//Enter your desired background colour below
define('BACKGROUND_COLOUR_HEX', '#FFFFFF');
//Enter your desired text colour below
define('TEXT_COLOUR_HEX', '#FF0000');
//Enter your desired shadow colour below
define('SHADOW_COLOUR_HEX', '#C0C0C0');
//Enter a font size
define('FONT_SIZE', 23);
//Enter the X coordinates of the main text below
define('MAIN_X', 20);
//Enter the Y coordinates of the main text below
define('MAIN_Y', 23);
//Enter your desired font below
define('FONT_TYPE', 'arial.ttf');
?>
第三个文件称为 count.txt,是存储访问者数量的地方。从 0 或您想要的数字开始。
第四个文件只是一个字体文件,在我的例子中是 arial.tff