为每个网页添加PHP页面浏览量计数器

oewdyzsn  于 2023-01-29  发布在  PHP
关注(0)|答案(3)|浏览(130)

我正在尝试完成的是一个简单的PHP页面计数器为我的每个PHP页面,我知道这可以用MYSQL数据库以及完成,但我只是想要一个简单的页面计数器与严格的PHP(我已经完成)。
我已经找到了一个脚本,工作,但它只显示一个页面的意见,我想知道,如果有一种方法来编辑代码,使每一个页面,我包括计数器,意见的数量将是不同的,为该页。
我找到要遵循的说明的网站是http://tutorial.world.edu/web-development/how-to-create-page-view-hit-counter-code-using-php-script/
这是我的代码,我根据自己的需要编辑了它:

function pageview_counter()
{
    if (isset($visitor)) {
        if ($visitor == "visited")
            include("pageview-counter.txt");
    } else {
        $file = fopen("pageview-counter.txt", "r+");
        $result = fread($file, filesize("pageview-counter.txt"));
        fclose($file);
        $result += 1;
        $file = fopen("pageview-counter.txt", "w+");
        fputs($file, $result);
        fclose($file);
        include("pageview-counter.txt");
    }
}

对于计数器:

<p class="num-of-views">Views: <strong><?php echo pageview_counter(); ?></strong></p>

我创建的文本文件在我的网站目录下的指示,我只是想知道如果我想要的实际上可以完成。任何帮助将不胜感激!

dbf7pr2w

dbf7pr2w1#

如前所述,MySQL数据库是更好的选择,但如果您坚持使用文件,我会使用自定义INI文件:

page1 = 0
page2 = 0
page3 = 0

你可以添加任意多的页面,当然也可以更改它们的名称。只需将其保存为pageCounts.ini。接下来你需要能够读写这个ini文件。我建议为此创建一个单独的PHP文件,并将其包含在页面中:

<?php

// Parse the ini file (Read)
$ini = parse_ini_file("pageCounts.ini");

// Save to ini file (Write)
function write_php_ini($array, $file = "pageCounts.ini")
{
    $res = array();
    foreach($array as $key => $val)
    {
        if(is_array($val))
        {
            $res[] = "[$key]";
            foreach($val as $skey => $sval) $res[] = "$skey = ".(is_numeric($sval) ? $sval : '"'.$sval.'"');
        }
        else $res[] = "$key = ".(is_numeric($val) ? $val : '"'.$val.'"');
    }
    safefilerewrite($file, implode("\r\n", $res));
}

function safefilerewrite($fileName, $dataToSave)
{    if ($fp = fopen($fileName, 'w'))
    {
        $startTime = microtime(TRUE);
        do
        {            $canWrite = flock($fp, LOCK_EX);
           // If lock not obtained sleep for 0 - 100 milliseconds, to avoid collision and CPU load
           if(!$canWrite) usleep(round(rand(0, 100)*1000));
        } while ((!$canWrite)and((microtime(TRUE)-$startTime) < 5));

        //file was locked so now we can store information
        if ($canWrite)
        {            fwrite($fp, $dataToSave);
            flock($fp, LOCK_UN);
        }
        fclose($fp);
    }

}

?>

来源:How to read and write to an ini file with PHP
将其另存为iniOperations.php并将其包含在需要计数器的页面中。将page1更改为包含计数器的页面。

<?php

// Include iniOperations.php if it isn't included yet
require_once "iniOperations.php";

// Show the current number of visits:
echo "Number of visits to this page: ". $ini["page1"];

// Increase the number of visits by 1 and write to ini file
$ini["page1"]++;

write_php_ini($ini);

?>
xkftehaa

xkftehaa2#

别忘了:apache用户的读/写权限。
万维网数据用户?
作为根用户,chown www-data:www-data插入文件名
它解决了我的问题与简单的php读/写操作
在文本文件中。

mlnl4t2r

mlnl4t2r3#

带样式的访客计数代码

<?php
// disable cache so that the image will be fetched every time
$timestamp = gmdate("D, d M Y H:i:s") . " GMT";
header("Expires: $timestamp");
header("Last-Modified: $timestamp");
header("Pragma: no-cache");
header("Cache-Control: no-cache, must-revalidate");

// set the content type to be an image
header("Content-type: image/svg+xml");

// increment the file and return the current number
//function incrementFile($filename): int
function incrementFile($filename)
{
    // if the file exists
    if (file_exists($filename)) {
        // open the file for reading and writing
        $fp = fopen($filename, "r+") or die("Failed to open the file.");
        // lock the file so it can't be opened by another user
        flock($fp, LOCK_EX);
        // read the file and add 1
        $count = fread($fp, filesize($filename)) + 1;
        // delete the contents
        ftruncate($fp, 0);
        // go to the beginning of the file
        fseek($fp, 0);
        // write the new count
        fwrite($fp, $count);
        // unlock the file
        flock($fp, LOCK_UN);
        // close the file
        fclose($fp);
    }
    // create the file if it doesn't exist
    else {
        // set the contents of the file to the number 1
        $count = 1;
        file_put_contents($filename, $count);
    }
    // return the current file contents
    return $count;
}

// short numbers from https://stackoverflow.com/a/52490452/11608064
function shortNumber($num)
{
    $units = ['', 'K', 'M', 'B', 'T'];
    for ($i = 0; $num >= 1000; $i++) {
        $num /= 1000;
    }
    return round($num, 1) . $units[$i];
}

// get contents of a URL with curl
//function curl_get_contents($url): string
function curl_get_contents($url)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_VERBOSE, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $response = curl_exec($ch);
    curl_close($ch);
    return $response;
}

// increment the file and get the current count
$message = incrementFile("views.txt");

// set parameters for the shields.io URL
$params = [
    "label" => "Views",
    "logo" => "github",
    "message" => shortNumber($message),
    "color" => "purple",
    "style" => "for-the-badge"
];

// build the URL with an SVG image of the view counter
$url = "https://img.shields.io/static/v1?" . http_build_query($params);

// output the response (svg image)
echo curl_get_contents($url);
?>

您可能需要手动创建与index.php相邻的views.txt文件,并根据服务器配置启用其写入权限。

警告不建议使用Heroku托管此项目,因为它具有临时文件系统,并且在刷新源代码时将删除views.txt

相关问题