I have a file in a directory that I would like to replace with a current version every hour. I use `shell_exec()` to `zcat` the file and the process of unzipping it and writing it takes about 4 minutes. Prior to this reading and writing, I record the name of the file which is already in the directory so that I can `unlink` it after the new file is done writing. But it doesn't happen in the order I would like it to. PHP executes the deletion while the `shell_exec` is processing. Only after four minutes of an empty directory do I see the newlly written file. Is there any way I can defer this deletion or make it a callback to both reading and writing processes?

```
$log_files = scandir("/cached_logs/");

foreach ($log_files as $key => $val){ 
    //non-secure file to delete 
    if (preg_match("/^access/", $val)){ 
        $log_to_delete= $val; 
    }
}

$ssl_command_string = "zcat log." . $datetime . ".gz";

//execute
$ssl_res = shell_exec($ssl_command_string);

//build the local directory and append the new file name with the current $datetime
$cached_ssl_file_name = "/cached_logs/log." . $datetime . ".txt";

//open the file handle
$new_ssl = fopen($cached_ssl_file_name, 'w') or die("can't open file");

//write
fwrite($new_ssl, $ssl_res);

//close
fclose($new_ssl);

unlink("/cached_logs/" . $log_to_delete); //this is defined properly above, I just didn't post it as it's irrelevant to the problem.

```

Edit:
cleared some things up and corrected syntax errors resulting from scrubbing out information