Store variable using sessions

房东的猫 提交于 2019-12-20 02:54:30

问题


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:


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();


来源:https://stackoverflow.com/questions/28665244/store-variable-using-sessions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!