Serializing PHP Values into a File or a Database

Serializing PHP Values into a File or a Database

Last updated:

I have met with the need to save PHP values (into files and/or database) and will document the approaches I've taken here.

serializing and deserializing an array with strings

worked ok

$arr = [
    'foo'=>'foo',
    'bar'=>'bar'
];
$ser = serialize($arr);//if you dump $ser, you'll see it's a string
$new_arr = unserialize($ser);
$new_arr['foo'] = 'baz';//works ok

serializing into a file

(the extension doesn't need to be .ser. I've just used it to remind myself that it's not a regular text file.)(notice the 'wb' mode on opening the file. I thought this was better because, as stated in the docs, the serialized file is actually a binary file.)

$arr=[
    'foo'=>'bar',
    'baz'=>'quux'
];
$ser = serialize($array);
$file = fopen('path/to/file.ser', 'wb');
fwrite($file, $ser); 

serializing an array with string and storing it on a db

(stored the output from serialize() into a text column on mysql)

$result = mysqli_query($conn,'select config from options where module_name=\'test2\'');
$data = mysqli_fetch_assoc($result);
$another_array = unserialize($data['config']);
$another_array['foo']='new_stuff';//works ok

serializing an array with string onto a BLOB-type column on a DB

The official docs page on serialize says it's better to store this kind of data on a BLOB-type column if you want to save it onto a database so I've tested it too.

serializing an object (or an array that contains objects) on a database

I've saved it onto a BLOB column. CAREFUL: This only worked because the Class definition is on the same page. If you serialize an object in one page and then try to un-serialize it on another page, it will only work if you include the class file on that page too.

Class Foo{
    public $bar;
    public function echoStuff(){
        echo $this->bar;
    }
}
$obj = new Foo;
$obj->bar = 'old stuff';
$ser = serialize($obj);
//saved it onto a db - i won't show that code
$result = mysqli_query($conn,'select config from options where module_name=\'test6\'');
$data = mysqli_fetch_assoc($result);
$new_obj = unserialize($data['config']);
$new_obj->echoStuff(); // prints "old stuff"
$new_obj->bar='new stuff';
$new_obj->echoStuff(); // prints "new stuff"