Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Is there a command that can delete the contents of a file without opening it?

Tags:

php

Is there any way to remove the contents of an file in php, do we have any php command that does that, I know unlink but I do not want to delete the file instead I just want to remove the contents of that file.

I have an file which I pass while called a getCurrentDBSnap function, it takes in the file from /home/test/incoming folder and populates currentDB table state into the file using fputcsv and puts back file to /home/test/outgoing.

Currently file stays in incoming folder and when I can call the function getCurrentDBSnap it would take the file and override with latest state of DB into it.

Q: My question is, is it possible instead of overwriting the file, we can remove the content of file after ever getCurrentDBSnap such that file in incoming folder would be always empty ?

Hope it makes sense :)

like image 359
Rachel Avatar asked Nov 30 '22 18:11

Rachel


2 Answers

Try file_put_contents($filename, "");

or

unlink($filename);
touch($filename);
like image 98
Byron Whitlock Avatar answered Dec 06 '22 16:12

Byron Whitlock


ftruncate — Truncates a file to a given length

Example

$handle = fopen('/path/to/file', 'r+');
ftruncate($handle, 0);
fclose($handle);

But you have to open the file.

like image 43
Gordon Avatar answered Dec 06 '22 16:12

Gordon