Access kirby object from assets folder


Is there any way to access the kirby global object from a php function placed in the assets folder ?

This global function will be called from different pages using AJAX. That’s why I chose not to use a page method or a controller.

Thank you for your help.

If I were you, I’d put the logic into a route that you can then call from your script: Routing | Kirby CMS

Otherwise, you would have to bootstrap kirby into your external script, like in this example (How to migrate users | Kirby CMS), which makes sense for such on-off scripts, but for your use case, better go with option 1.

Thank you @texnixe
I’m not familiar with routing. I didn’t think that it could be used to call global function. I’m going to explore that option.

Routes are very powerful. You can do anything with them if you need logic to be available from a URL.

Note that you can’t use the $kirby variable outside of templates and snippets, but have to use kirby() instead or if you need it more often, store the object in a variable:

$kirby = kirby();
1 Like

I need to access POST data in my php script, is it possible with routes ?

Routes accept different methods, default is GET, but you can set your method with the method property:

Ok, I’m already trying. Thanks for your help !

The PHP script works well ! Even if the AJAX call throws a 404 in the console. Any idea to remedy to that error ?

Maybe if you post both the route and the script…

The AJAX call :

fetch(`${siteUrl}/update-data/${key}/${newQuantity}/${page}`, {
                method: 'GET'

The route / PHP script :

'routes' => [
          'pattern' => 'update-data/(:any)/(:any)/(:all)',
          'action'  => function ($key, $value, $page) {
            $kirby = kirby();
              $key => $value

Hm, is that your complete code? I would expect that your route returns something to the fetch request.

Apart from that, your PHP code is missing some check that the page exists before trying to update it, and ideally, you would wrap this update method in a try/catch block, so that you can return something useful to your JS script in case updating fails.

Something like this should work:

$kirby = kirby();

if ( $page = page($page) ) {
  try {
      $key => $value,
    return new Response('Page successfully updated', 'text/plain', 200);
  } catch( Exception $e) {
    return new Response($e->getMessage(), 'text/plain', 404);
} else {
  return new Response('Page does not exists', 'text/plain', 404);

Can’t access to my website anymore with this route Neither the panel. Every screen were blanks. I remove the code and it went to normal.

The fatal error seems to be caused by the return new Response.
Exception also causes the fail.

There were two syntax errors in my code above, please try again.

It works, thanks for your help !

1 Like