Инструменты пользователя

Инструменты сайта

  • Показать исходный текст
  • История страницы
  • Ссылки сюда
  • Оставить на чай
  • Экспорт в PDF
  • Наверх

  • wiki:devel:counter

    Счетчик посещений сайта Dokuwiki

    Простейший счетчик для сайта (подсчет посещения любой страницы) без базы данных. Существует масса способов реализации счетчика просмотров страницы на PHP и в основном они работают с базой данных. Но если вам нужно прикрутить по-быстрому к одной странице счетчик посещений, то этот скрипт будет вам полезен. БД он не использует, а создает текстовый файл, в котором и хранит информацию о количестве просмотров. И, как обычно, предлагаю посмотреть как это выглядит на фото или в низу станицы.

    Код счетчика

    PHP
    <?php 
    $file = file("count.txt");
    $count = implode("", $file);
    $count++;
    $myfile = fopen("count.txt","w");
    fputs($myfile,$count);
    fclose($myfile);
    ?>
    <span>Просмотров: <?=$count ?></span> // вывод счетчика

    Править будем файл tpl_footer расположенный Dokuwiki\lib\tpl\dokuwiki с добавление стиля:

    CSS
    .container {
        position: absolute;
        font-family: Georgia, 'Times New Roman', Times, serif;
    }
    .text-block {
        position: absolute;
        bottom: 0px;
        right: 4px;
        color: black;
    }

    в файле tpl_footer добавляем в блок <div class="buttons"> нижеприведенный код PHP

    PHP
            <a>
                <?php 
                    $file = file("count.txt");
                    $count = implode("", $file);
                    $count++;
                    $myfile = fopen("count.txt","w");
                    fputs($myfile,$count);
                    fclose($myfile);
                ?>
            <style>
                .container {
                position: absolute;
                font-family: Georgia, 'Times New Roman', Times, serif;
                }
                .text-block {
                position: absolute;
                bottom: 0px;
                right: 4px;
                color: black;
                }
            </style>
                <a class="container">
                    <span><img src="<?php echo tpl_basedir(); ?>images/button-yandex.png" width="85" height="15" alt="yandex" / >
                        <div class="text-block"><?=$count ?></div>
                    </span>
                </a>
            </a>

    В папку с картинками загружаем нашу иконку с размером 80px x 12px. и в строке кода <img src="<?php echo tpl_basedir(); ?>images/button-yandex.png" width="85" height="15" alt="yandex" / > прописываем путь к картинке. В моем случае это папка с шаблонами/картинки/.

    Я не стал стили (необходимы для наложения текста на картинку) выносить пока в отдельный файл, чтобы было все для примера в одном месте.
    Тут добавлен блок-контейнер (<a class="container">) для позиционирования в основном блоке (<div class="buttons">) шаблона и добавления шрифта и цвета текста. $file = file("count.txt"); создает файл в корне Dokuwiki с записями о посещении страниц, при желании можете изменить ее расположение.

    PHP
    <?php
    /**
     * Template footer, included in the main and detail files
     */
     
    // must be run from within DokuWiki
    if (!defined('DOKU_INC')) die();
    ?>
     
    <!-- ********** FOOTER ********** -->
    <footer id="dokuwiki__footer"><div class="pad">
        <?php tpl_license(''); // license text ?>
     
        <div class="buttons">
            <?php
                tpl_license('button', true, false, false); // license button, no wrapper
                $target = ($conf['target']['extern']) ? 'target="'.$conf['target']['extern'].'"' : '';
            ?>
            <a href="https://php.net" title="Powered by PHP" <?php echo $target?>><img
                src="<?php echo tpl_basedir(); ?>images/button-php.gif" width="80" height="15" alt="Powered by PHP" /></a>
            <a href="//validator.w3.org/check/referer" title="Valid HTML5" <?php echo $target?>><img
                src="<?php echo tpl_basedir(); ?>images/button-html5.png" width="80" height="15" alt="Valid HTML5" /></a>
            <a href="//jigsaw.w3.org/css-validator/check/referer?profile=css3" title="Valid CSS" <?php echo $target?>><img
                src="<?php echo tpl_basedir(); ?>images/button-css.png" width="80" height="15" alt="Valid CSS" /></a>
            <a href="https://dokuwiki.org/" title="Driven by DokuWiki" <?php echo $target?>><img
                src="<?php echo tpl_basedir(); ?>images/button-dw.png" width="80" height="15"
                alt="Driven by DokuWiki" /></a>
            <a>
                <?php 
                    $file = file("count.txt");
                    $count = implode("", $file);
                    $count++;
                    $myfile = fopen("count.txt","w");
                    fputs($myfile,$count);
                    fclose($myfile);
                ?>
            <style>
                .container {
                position: absolute;
                font-family: Georgia, 'Times New Roman', Times, serif;
                }
                .text-block {
                position: absolute;
                bottom: 0px;
                right: 4px;
                color: black;
                }
            </style>
                <a class="container">
                    <span><img src="<?php echo tpl_basedir(); ?>images/button-yandex.png" width="85" height="15" alt="yandex" / >
                        <div class="text-block"><?=$count ?></div>
                    </span>
                </a>
            </a>
        </div>
        <?php tpl_includeFile('footer.html'); ?>
    </div></footer><!-- /footer -->
    или скачать файл ''tpl_footer'' целиком и поместить в папку Dokuwiki\lib\tpl\dokuwiki.
    и нажав на картинку иконки сохранить как button-yandex.png в папке Dokuwiki\lib\tpl\dokuwiki\images.
    У кого текст убегает, ловим его в стиле:

    CSS
    .container {
        position: absolute;
        font-family: Georgia, 'Times New Roman', Times, serif; //шрифт
    }
    .text-block {
        position: absolute;
        bottom: 0px;  //устанавливает положение нижнего края
        right: 4px;   //расстояние от правого края родительского элемента
        color: black; //цвет текста
    }

    Ну и все…Наслаждаемся.

    Ссылка на источник кода

    Обсуждение

    Ваш комментарий:

    Внимание! Оставляя комментарий Вы соглашаетесь с пониманием и несете ответственность за свои действия гл.2 ст.18 Федерального закона №38-ФЗ «О рекламе» и ст.3 п.1 Федерального закона №152-ФЗ «О персональных данных»
    217 +5 = 
     
    wiki/devel/counter.txt · Последнее изменение: 2023/09/02 21:26 — vladpolskiy