How to use php serialize() and unserialize()

后端 未结 10 1882
Happy的楠姐
Happy的楠姐 2020-11-22 05:03

My problem is very basic.

I did not find any example to meet my needs as to what exactly serialize() and unserialize() mean in php? They ju

10条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 05:46

    Please! please! please! DO NOT serialize data and place it into your database. Serialize can be used that way, but that's missing the point of a relational database and the datatypes inherent in your database engine. Doing this makes data in your database non-portable, difficult to read, and can complicate queries. If you want your application to be portable to other languages, like let's say you find that you want to use Java for some portion of your app that it makes sense to use Java in, serialization will become a pain in the buttocks. You should always be able to query and modify data in the database without using a third party intermediary tool to manipulate data to be inserted.

    it makes really difficult to maintain code, code with portability issues, and data that is it more difficult to migrate to other RDMS systems, new schema, etc. It also has the added disadvantage of making it messy to search your database based on one of the fields that you've serialized.

    That's not to say serialize() is useless. It's not... A good place to use it may be a cache file that contains the result of a data intensive operation, for instance. There are tons of others... Just don't abuse serialize because the next guy who comes along will have a maintenance or migration nightmare.

    A good example of serialize() and unserialize() could be like this:

    $posts = base64_encode(serialize($_POST));
    header("Location: $_SERVER[REQUEST_URI]?x=$posts");
    

    Unserialize on the page

    if($_GET['x']) {
       // unpack serialize and encoded URL
       $_POST = unserialize(base64_decode($_GET['x']));
    }
    

提交回复
热议问题