开发者

Emptying a file with php [duplicate]

开发者 https://www.devze.com 2023-02-10 00:20 出处:网络
This question already has answers here: 开发者_高级运维 Closed 12 years ago. Possible Duplicate: PHP: Is there a command that can delete the contents of a file without opening it?
This question already has answers here: 开发者_高级运维 Closed 12 years ago.

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号