Global variable for Kirby 3

Hi there, I have geoip detect code that I use on different pages, templates.

$json = file_get_contents('https://geoip-db.com/json');
$location = json_decode($json);
$countrycode = $location->country_code;

I was try to put it in site controller, and snippet, but without this code in template controller kirby didn’t see $countrycode variable…

Maybe I need somehow initiate this variable in snippet, of create plugin? Any suggestions?

You could create a function in a plugin that return the countrycode in a plugin, then call the function wherever you need the code

function getCountryCode() {
  $json = file_get_contents('https://geoip-db.com/json');
  $location = json_decode($json);
  $countryCode = $location->country_code;
  return $countryCode;
}

In any controller:

$countryCode = getCountryCode();
2 Likes

Is it possible to use it in snippets, not in controllers?

You can use it anywhere.

1 Like

Not sure that im do it in correct way,
Im create folder plugins/geoip then create index.php
And add next code there:

<?php

Kirby::plugin('wildthing/geoip', [
  'routes' => function ($kirby) {
    return [
      [
        'pattern' => '(:any)',
        'action' => function getCountryCode() {

		  $json = file_get_contents('https://geoip-db.com/json');
		  $location = json_decode($json);
		  $countrycode = $location->country_code;
		  return $countryCode;

        }
      ]
    ];
  }
]);

Is it correct? Because i’ve have 500 error)

No, that doesn’t make sense, why do you want to create a route? Just an index.php in a folder with a function, e.g.

site/plugins/myfunctions/index.php

<?php
function getCountryCode() {
  $json = file_get_contents('https://geoip-db.com/json');
  $location = json_decode($json);
  $countryCode = $location->country_code;
  return $countryCode;
}

Without the Kirby::plugin() wrapper or anything else.

On a side note, the routes array doesn’t accept a callback , just an array of routes.

3 Likes

Great!!! Thanks a lot.

Is it possible to make this function, or variable not cacheble?