Save a PHP variable even when reload

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

Answers (3)

Niclas Larsson
Niclas Larsson

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

Toretto
Toretto

Reputation: 4711

You can try session with ajax.

  1. save it as a session variable and retrieve it over AJAX each time the page loads.
  2. save it as cookie (might as well do the javascript approach if you're going to cookie it.

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

tuxtimo
tuxtimo

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

Related Questions