简体   繁体   中英

Passing class Instances and other data between pages in PHP

I've been looking into the problems of having persistent data available between pages in PHP. This particularly applies to objects that have been set up in one page that need to be accessed later. It seems this is more difficult than I assumed it would be, but there are several ways this could be done, although they all seem a bit awkward to use especially when the data gets quite complex:

  • Passing the data via $_GET or $_POST to the next page
  • Copying the data to a database and retrieving it in the next page
  • Putting the data in a session or cookie
  • Serializing the object and recreating it with the same parameters and values

These all seem quite laborious as they mostly rely on having to deconstruct your existing data structure and then rebuild it again on the next page. I assume this is to reduce memory requirements of the PHP server by purging data from one page as soon as its closed and starting with a 'clean slate'.

Is there a more direct way of passing larger data structures between pages in PHP?

Many thanks, Kw

I assume this is to reduce memory requirements of the PHP server by purging data from one page as soon as its closed

Nope, this is not because of memory efficiency concern. This is because HTTP protocol is stateless. Each request must carry all information that is necessary to fulfill it.

Counter-example to your proposed scenario:

  1. let's suppose Alice visits page A, some objects are created and you want them to be available in page B.

  2. You track a visit to page B.

    2.1. But it's not Alice, it's Bob. How do you determine which objects to show and where do you get them from?

    2.2. It is Alice again, but the request arrived to another machine from your 1000 server farm. Naturally, you don't have original PHP objects. What do you do now?

If you use $_GET or $_POST you are limited to non-sensitive data and you expose your objects to any user. You don't want that.

Cookies are limited in size

cookies are usually limited to 4096 bytes and you can't store more than 20 cookies per site.

The best way to persist objects between requests (for the same user) is to use Sessions. There are already session save handlers for memcached, redis, mysql etc. You can also write your own if you need something custom.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM