[英]Hit counter for each page with PHP
我想在我的網頁上集成一個計數器,至此我已經完成了,以便計數器可以工作。 但是我真正想要的是此計數器專門針對每個id
生成的每個頁面
<?php
session_start();
$counter_name = 'counter'.$id.'.txt';
// Check if a text file exists. If not create one and initialize it to zero.
if (!file_exists($counter_name)) {
$f = fopen($counter_name, "w");
fwrite($f,"0");
fclose($f);
}
// Read the current value of our counter file
$f = fopen($counter_name,"r");
$counterVal = fread($f, filesize($counter_name));
fclose($f);
// Has visitor been counted in this session?
// If not, increase counter value by one
if(!isset($_SESSION['hasVisited'])){
$_SESSION['hasVisited']="no";
$counterVal++;
$f = fopen($counter_name, "w");
fwrite($f, $counterVal);
fclose($f);
}
else {
$counterVal++;
$f = fopen($counter_name, "w");
fwrite($f, $counterVal);
fclose($f);
}
$counterVal = str_pad($counterVal, 5, "0", STR_PAD_LEFT);
$chars = preg_split('//', $counterVal);
$im = imagecreatefrompng("canvas.png");
$src1 = imagecreatefrompng("$chars[1].png");
$src2 = imagecreatefrompng("$chars[2].png");
$src3 = imagecreatefrompng("$chars[3].png");
$src4 = imagecreatefrompng("$chars[4].png");
$src5 = imagecreatefrompng("$chars[5].png");
imagecopymerge($im, $src1, 0, 0, 0, 0, 15, 15, 100);
imagecopymerge($im, $src2, 15, 0, 0, 0, 15, 15, 100);
imagecopymerge($im, $src3, 30, 0, 0, 0, 15, 15, 100);
imagecopymerge($im, $src4, 45, 0, 0, 0, 15, 15, 100);
imagecopymerge($im, $src5, 60, 0, 0, 0, 15, 15, 100);
// Output and free from memory
header('Content-Type: image/png');
echo imagepng($im);
imagedestroy($im);
?>
使用此代碼,我只能看到主頁的匹配。 它在每個頁面上顯示相同的數字,例如ex。
page 1 count: 100
page 2 count: 100
在刷新50x第1頁后
page 1 count: 150
page 2 count: 150
文件名為counter.php
並使用以下代碼在模板文件上實現
<img style="padding-left: 2px;" alt="Hit counter" src="http://www.example.com/counter/counter.php" />
我一直在尋找解決方案,但到目前為止尚未找到任何解決方案。
提前致謝。
最好的祝福,
BujarA。
對於您使用的未定義$id
變量,您可以使用例如來自服務器的路徑信息:
<?php
session_start();
$id = preg_replace('[^\w-]', '', $_SERVER['PATH_INFO']);
$counter_name = 'counter' . $id . '.txt';
// etc.
請注意,為了避免出現問題,我刪除了所有特殊字符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.