代码之家  ›  专栏  ›  技术社区  ›  BujarA

用PHP为每个页面点击计数器

  •  0
  • BujarA  · 技术社区  · 8 年前

    我想在我的网页上集成一个计数器,因为我已经这样做了,所以计数器可以工作。但我真正想要的是,这个计数器对于每个要生成的页面都是特定的 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);
    ?>
    

    前任。

    page 1 count: 100 
    page 2 count: 100
    

    刷新50倍后第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" />
    

    我一直在寻找解决方案,但至今没有找到任何解决方案。
    提前谢谢。

    顺致敬意,

    1 回复  |  直到 8 年前
        1
  •  0
  •   jeroen    8 年前

    对于未定义的 $id 您正在使用的变量,例如,您可以使用来自服务器的路径信息:

    <?php
    
    session_start();
    
    $id = preg_replace('[^\w-]', '', $_SERVER['PATH_INFO']);
    
    $counter_name = 'counter' . $id . '.txt';
    
    // etc.