Store variable using sessions

2019-02-26 09:06发布

I have a variable which is updated on every page shift, but I want to store the value in the first call for good somehow.

The variable is e.g

   $sizeOfSearch = $value['HotelList']['@activePropertyCount'];

First time the page loads it's 933, on next page the same value is retrieved but it's now different e.g 845. This goes on page for page.

What I want is to store 933 for good. So I can show this number on every page.

Can I somehow store the first time this value is retrieved ? (I get the value via REST request)

Sessions maybe or ?

1条回答
时光不老,我们不散
2楼-- · 2019-02-26 09:24

session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.

When session_start() is called or when a session auto starts, PHP will call the open and read session save handlers. These will either be a built-in save handler provided by default or by PHP extensions (such as SQLite or Memcached); or can be custom handler as defined by session_set_save_handler(). The read callback will retrieve any existing session data (stored in a special serialized format) and will be unserialized and used to automatically populate the $_SESSION superglobal when the read callback returns the saved session data back to PHP session handling.

So, on every page make sure to start it with:

<?php
session_start();

Then, you set the value like this:

if(!isset($_SESSION['name'])) {
    $_SESSION['name'] = $sizeOfSearch;
}

Whenever you need the retrieve the value use this:

print $_SESSION['name'];

This session will keep store the variable as long as you don't destroy it. Code for destroying a session:

session_destroy();
查看更多
登录 后发表回答