How to save persistent values in PHP and remove all the persistent values on tab close

I have an calendar application that does look like this:
Calendar app.

The function I am implementing is the navigation through the months (previous month/next month) function.

During the implementation I have encountered a few problems:

  1. PHP cannot easily persist variables.
  2. Persistent values have to be deleted/removed when closing the tab/opening the page for the first time.

Adressing Issues
2. There are several ways to persist a variable:

Starting a session

session_start();
$_SESSION["favcolor1"] = "green";
echo $_SESSION["favcolor1"];

Issues

  1. The value persists, but the variables are nowhere to be found in the app memory.
  2. When closing the tab, the value remains, which is a problem.

Saving as cookie

setcookie("TestCookie", "Hello World", time()+3600);
echo $_COOKIE["TestCookie"];

The variable can be found in the app storage

Issues

  1. If there is an echo before setcookie, it will be cancelled, i.e. it will not be executed. (xDD).
  2. When closing the tab, it persists, which is a problem.

Other possible solutions

  1. External files, which should work with include and `define
  2. Using a database to keep track of persistent variables.

2. Tab close event can be done via JS with beforeunload ??
Is there a way to do it via PHP ?

The problem persists:

  1. The variable should persist, which can be solved
  2. The values should be cancelled when the tab is closed.