Server side visit counter for PHP applications.

2.0.0 2019-12-20 13:21 UTC

This package is auto-updated.

Last update: 2021-02-20 16:30:29 UTC


Build Status

Server side visit counter for PHP applications

composer require petrhejna/server-side-page-visit-counter


Building dependencies

Building dependencies using Airtable (you can use your own storage by implementing PageViewStorage interface):

    $airtable = new TANIOS\Airtable\Airtable([
        'api_key' => '****',
        'base' => 'Your Base',
    $pageViewStorage = new AirtablePageViewStorage('page_views', $airtable);
    $pageViewFromRequestFactory = new PageViewFromRequestFactory(...); // fill dependencies
    $pageViewCounter = new PageViewCounter(['/ignored/'], $ageViewStorage);
    $pageViewCounterMiddleware = new PageViewCounterMiddleware($pageViewCounter, ...);

If you are using Nette Dependency Container you can use this example of neon configuration:

    airtable: Guym4c\Airtable\Airtable(%airtable.apiKey%, %airtable.base%)
    - PetrHejna\ServerSidePageViewCounter\PageViewFromRequestFactory
    - PetrHejna\ServerSidePageViewCounter\Storage\Airtable\FilterFormulaFactory
    pageViewStorage: PetrHejna\ServerSidePageViewCounter\Storage\Airtable\AirtablePageViewStorage('page_views', @airtable)
    - PetrHejna\ServerSidePageViewCounter\PageViewCounter(['/ignored/'], true, @pageViewStorage) # if second parameter 'true`, only <400 responses will be counted

Using counter

Example from PSR based application using middleware architecture:

final class PageViewCounterMiddleware implements Middleware
    /** @var PageViewCounter  */
    private $pageViewCounter;

    public function __invoke(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface {
        $next = $this->next;
        $innerStackResponse = $next($request, $response, $state);
        // It is IMPORTANT to have it after $next(...) to work with final reponse of your middleware stack.
        $responseAfterPageViews = $this->pageViewCounter->countVisit($request, $innerStackResponse);
        return $responseAfterPageViews;


Airtable storage is implemented in the way, that for already existing visit does NOT create new records but adds +1 to count field and updates viewedAt time.

Tracking visitors via cookie

This library adds visitorId into cookie. Method countVisit returns ResponseInterface object with Set-Cookie header for visitorId cookie. If no cookie set, the counter will generate new one.

Ignored paths

Sometimes, there are paths that you dont want to track. You can set array of ingored paths via first argument of PageViewCounter constructor.