Php using unserialize () and serialize () changing values ​​in saved file

I have a serialized array of values ​​stored in a file and need to change the value of one of the variables. In the example, I change the value of $ two and then save the entire array back to file with the new value.

Is there a more efficient way to change just one value without having to read and write the entire file / array.

$data = file_get_contents('./userInfo');

$data = unserialize($data);
extract($data);
$two="this is a altered value";

 $userData = array(
        'one'          => $one,
        'two'          => $two,
        'three'        => $three
        );

 $file=fopen("../userInfo",'w');
        fwrite($file, $userData);
 fclose($file);

      

+2


a source to share


3 answers


Option 1: a database row for each array record.

Option 2: a separate file for each array entry, using the file name instead of the array key. Basically use a directory on the filesystem as a very simple database.



Option 3: Fixed size writes in a flat file, so you can multiply the array index by the read / write block size. You will have to trim data that is larger than the block size you selected. Basically use one file as a very simple database.

+1


a source


You don't need to use extract()

rebuild $userData

like this, just access the array key you want . Alternatively, you can save multiple steps using file_put_contents ()

This function is identical to calling fopen (), fwrite (), and fclose () to write data to a file sequentially.



New code:

$filePath = './userInfo';

$data = unserialize( file_get_contents( $filePath ) );

$data['two'] = "this is a altered value";

file_put_contents( $filePath, serialize( $data ) );

      

+6


a source


If you want to do manual parsing of strings, you only need to rewrite the rest of the file content that occurs after the value if you change the length of the string. If you don't change the length of the string, you can edit it in place. If this serialized data file is not very large, I really doubt you will do anything, but make it slower.

I wouldn't bother. If this causes a performance issue, I would seriously consider a different storage format.

0


a source







All Articles