Suprisingly there are times when a database is not available to persist a data structure through the script’s life cycles. Thankfully PHP has a cool and easy way to serialize/unserialize an array such that I can be stored in a file on disk.
To serialize an array simply call the serialize function and pass in the desired data structure as an argument. In return PHP will spit out an encoded version as a string, which then can be written to file.
$s = serialize($registered); ftruncate($handle, 0); fseek($handle, 0); fwrite($handle, $s);
To recover the data into an array simply unserialize the contents of the file.
if (file_exists(FILE)) { $handle = fopen(FILE,'r+') or die("ERROR: Cannot open file."); $s = fread($handle, filesize(FILE)); } $registered = unserialize($s);
This method would also work for non file I/O, but rather NIO to transfer the data over the wire. But this day and age you might as…
View original post 8 more words
Advertisements