So I have a file called cache, which stores traffic analysis of a site, using multidimensional arrays.
cache.php
$traffic_array=array("date_ip_uniqueNU"=>array("pageviews"=>34,"time_enteredOnsite"=>"12:00"),"date_ip_uniqueNU"=>array("pageviews"=>34,"time_enteredOnsite"=>"12:00"));//ect ect
Now, I need to somehow append to the array above.
I could simply just read the whole file, go through and rebuild the array in a foreach loop, and then just re-write the whole file, something like this:
include('cache.php');
foreach($traffic_array as $mainKey){
$rebuild_contents.="array("something"=>array("pageviews"=>".$mainKey['pageviews'].","time_enteredOnsite"=>".$mainKey['time_enteredOnsite'].");"//so I'm just building a string containing all the code to re-write the file.
}
//then write to the file
$file="cache.php";
$content_to_put"\<? \$traffic_array=\"$rebuild_content\";"
file_put_contents($file,$content_to_put);
//NOTE: I just quickly wrote this up now, so expect syntax errors.
So do you see what I’ve done above – Simply rebuild the array contents into a string, and then write that string into the cache file.
But, I’m sure there is a much better approach to this, so can someone help me out?
Thank you! xD
EDIT: Also a problem with the method above, If this process was to happen multiple times, at the EXACT same millisecond – something would mess up, right?
It’s very, hm, strange method of caching.
Let suppose that you wish to change some php code in the file.
file_put_contents have ability to append the data to end of file, call this method with flag FILE_APPEND (details).
You may change method of defining array to like this:
And then you just add content to end of file like this
But if you may not change method of defining the array traffic_array then file_put_contents not for you. Use
fopen()with flag ‘r+’, usefseek()for move a pointer to to correct place for put new data at the file,fwrite()for write only new data, andfclose().Changing of input file can cause huge problems.
Right, read about file locking.