PHP操作顺序有什么问题?

I have a main script where I delete (unlink) a file. Then, in some script I include later in that main script, I write to that file (to the file with the same name as that deleted anyways, because it should already be gone by now).

What's happening is, that after the main script is run, the file is deleted. As is the unlink operation took place after writing to the file. The same think happens, when I truncate the file in the main script (by overwriting it with empty string) and later write to that file. The result is, that the file is empty (as if truncating the file took place after writing, but the literal order in code is reversed).

What can be wrong here? Or if it's not, why does it work that way?

EDIT:

first (in main script):

 unlink($config['directory'].'logs/info.txt');

then (in some include script):

 $f = fopen($config['directory'].'logs/info.txt', "w");
 fwrite($f, "Text"); 
 fclose($f);

I thought there may be some common mistake, that you could point out (like not calling fclose or something). So probably I have to investigate this closer (but I am sure no other operation on this file is made, because I used some unique name of the file, an the same thing happen).

How do you write to the file later? file_put_contents() is one way (and I barely use anything else any more) but if you use fopen/fwrite and forget the fclose that might cause problems like this.

It's impossible to give a definite answer without actually seeing the code, but one possibility is that there's a resource request from the client happening in the background that's causing the file to be deleted after the main request has completed.

Try using stack traces in the part of the script that deletes the file to identify how it's being invoked again; see debug_backtrace or debug_print_backtrace.

Remove the .txt from the fopen - mode paramater

$f = fopen($config['directory'].'logs/info.txt', "w");

http://php.net/manual/en/function.fopen.php

Just a thought, but have you tried flushing the output? You can use fflush($f); to force php to write all buffered data to the file.

Of course, you shouldn't actually need this - in fact opening it with the 'w' flag truncates the file anyway. Are you sure it's being opened correctly? Maybe try something like this:

$f = fopen($config['directory'].'logs/info.txt', "w");
if($f === false)die('File opening failed!');
fwrite($f, "Text"); 
fflush($f);
fclose($f);