在php中存储和附加文件

I have an app_id and a current date. actually I want to update my database if the current date and the stored date is greater than 4. I'm doing this:

$app_id = $_GET['ap'];
$current_date=date('d');
$a = array($app_id => $current_date);
$fp = fopen("time.txt",'r');
$last_run = unserialize(file_get_contents("time.txt"))[$app_id];
if(abs($last_run-$current_date) > 2)
{
    $fp = fopen("time.txt", 'w'); 
    fwrite($fp, serialize($a));
}

But the problem in this is when i switch the app it will again update the database because I'm using writing mode which is over writing the text file. I can use append mode. then how can i search in the array stored in the file and get that particular date corresponding that app_id and then append that date suitably. Thanks in advance

You need to read the file and unserialize the whole array into a variable, then you can test and update any part of the array and then write the whole array back to your file.

Also file_get_contents() and file_put_contents() do not need you to open a file handle it does it all internally.

$app_id       = $_GET['ap'];
$current_date = date('d');

$last_run = unserialize(file_get_contents("time.txt"));

if(abs($last_run[$app_id] - $current_date ) > 2 ) { 
    // change the last run date for this app
    $last_run[$app_id] = $current_date;

    file_put_contents('time.txt', serialize($last_run)); 
}

You really ought to be doing some checking in here as well.

  • That 'ap' is being passed to the script in the $_GET array
  • That the $last_run array actually contains a $app_id occurance