Reputation: 569
Can someone tell how to get a PHP variable even when you reload the page? I have tried with the session but it seems that the value is changed when the page is refreshed.
Upvotes: 1
Views: 5494
Reputation: 1317
<?php
session_start();
if( empty($_SESSION['test']) ) {
$_SESSION['test'] = date( 'Y-m-d H:i:s' );
}
echo $_SESSION['test'];
The first time this script is executed the current datetime will be assigned to the test key (and echoed out). Next time you run this script the old date will be echoed.
Upvotes: 1
Reputation: 4711
You can try session with ajax.
Any PHP approach would be clunky as you'd have to first send the value of the variable to a PHP script over AJAX, then retrieve it over AJAX after reload.
Or you could save it as a property of the page's local storage.save it as cookie.and append the variable to the URL hash so it can access by location.hash
after the browsers reload.
Upvotes: 0
Reputation: 2790
Session are what you want. Look at the following code:
<?php
// start session
session_start();
$var1 = "Hello World";
// save variable you want to have after the reload
$_SESSION["myvar"] = $var1;
// echo session value
echo $_SESSION["myvar"];
?>
Upvotes: 0