Possible Duplicate:
PHP: Is there a command that can delete the contents of a file without opening it?
How do you empty a .txt file on a server with a php command?
Here's a way to only emptying if it already exists and that doesn't have the problem of using file_exists
, as the the file may cease to exist between the file_exists
call and the fopen
call.
$f = @fopen("filename.txt", "r+");
if ($f !== false) {
ftruncate($f, 0);
fclose($f);
}
Write an empty string as the content of filename.txt
:
file_put_contents('filename.txt', '');
$fh = fopen('filename.txt','w'); // Open and truncate the file
fclose($fh);
Or in one line and without storing the (temporary) file handle:
fclose(fopen('filename.txt','w'));
As others have stated, this creates the file in case it doesn't exist.
Just open it for writing:
if (file_exists($path)) { // Make sure we don't create the file
$fp = fopen($path, 'w'); // Sets the file size to zero bytes
fclose($fp);
}
First delete it using unlink()
and then just create a new empty file with the same name.
With ftruncate()
: http://php.net/ftruncate
you can use the following code
`
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = "";
fwrite($fh, $stringData);
fclose($fh);
` It will just override your file content to blank
精彩评论