Passing Variables from snippet to snippet / Globally?

Is there away to setup Global variables, I’ve searched and see a lot of people asking but so many different suggestions but no definitive answer?

I have a dynamic variable in the ‘head’ snippet which I need to pass through to the ‘footer’ snippet.

My page templates are build like this:



page content


I have a variable in the ‘head’ snippet:

$msg = "";

Which sometimes displays a message:

$msg = "This is the message";

In the footer snippet I need to pass in and echo that variable if it isn’t empty:

<?php if (!empty($msg)) { echo $msg; } ?>

I know I can pass it from the page the the snippet using:

<?php snippet('footer', ['msg' => $msg]) ?>

But as the variable isn’t on the page then I’m not sure how to pass the variable from snippet to snippet?

What sort of content is stored in the variable, i.e. where does it come from? Do you need this variable in every template?

There are different ways to store such variable, from config options, controllers (or shared controllers) to session data. Using global variables is generally something that should be avoided.

Funny you should mention, it is actually the $msg variable from the login error on the login script you just helped me fix.

Ok, so this login thingy is on every single page? But since your script creates a new session, you might as well store you message in the session in the header, then retrieve it in the footer.

The login is on every page on a popup modal, all the main navigation is shown but only some links work and some don’t, the ones that don’t launch the login modal when they are clicked (click bait).

The head has all the login php from the last post and the footer contains the modal, if the login information is wrong when the page is submitted the modal stays open and the error message appears.

Head snippet:

if(isset($_POST['username'])) {

    if($userinfo[$_POST['username']] ?? '' === md5($_POST['password'])) {
	    $_SESSION['username'] = true;
    else {

Footer snippet:

<?php if (!empty($msg)) { echo $msg; } ?>

I need to pass variable through to the footer snippet.

As I said, store it in the session

else {

Then in the footer check if the message key is set and not empty.
Initialize empty key in header or remove value from session on successful login.

Thanks! Worked great.