1

I know that by using $_SESSION, one can store values over time. The default time is 1440 seconds = 24 minutes. I would like my values to be stored: for a longer time/until the browser has been closed.

Let's say I want to store the a boolean value and string value. Is session the best way?

For example: $_SESSION["value"] = true; and $_SESSION["value2"] = "my_string";?

Is session the best way, or are there any other good/better solutions? The values has to be available for all the pages (.php) on my website.

Ambrish Pathak
  • 3,813
  • 2
  • 15
  • 30
Erik Auranaune
  • 1,384
  • 1
  • 12
  • 27

2 Answers2

0

You can use cookies to store data for longer period of time. so using cookies would be like

Set Cookie

<?php
$cookie_name = "value2";
$cookie_value = "my_string";
//Cookie to hold true false can set using 0 or 1 like 
//setcookie('value', '0'); 0 for false, 1 for true

setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>

Retrieve Cookie value

<?php
if(!isset($_COOKIE[$cookie_name])) {
     echo "Cookie '" . $cookie_name . "' is not set!";
} else {
     echo "Cookie '" . $cookie_name . "' is set!";
     echo "Cookie Value is: " . $_COOKIE[$cookie_name];
}
?>

Setting and retrieving cookie for boolean

<?php
$CookieVar = true;

// setting the cookie
setcookie('myCookie', $CookieVar ? '1' : '0'); //set '1' if true else set '0'

if (isset($_COOKIE['myCookie']) AND $_COOKIE['myCookie'] === '1') {
    
    echo 'true';

} else {
    
    echo 'false';
}

?>

Screenshot

enter image description here

Ambrish Pathak
  • 3,813
  • 2
  • 15
  • 30
0

You can use the local storage for saving the data and for using it from any page on the website.

Using Javascript

window.localStorage.setItem(key, value);

This key can be removed using

window.localStorage.removeItem(key, value);

You can get the key value using

window.localStorage.getItem(key);
r.k
  • 97
  • 1
  • 2
  • 6
  • Correct me if I am wrong, but can't you just change the values in Dev tools(F12). And how long is this stored? Will it be removed when restarting browser? – Erik Auranaune Sep 23 '20 at 19:06