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
Perhaps this is work-arround if exec is allowed .. for ex on linux :
<?
shell_exec("rm -rf " . $filename " && touch ".$filename);
?>
This will remove your file and then create it again, so it will "appear" that you emptied the content, this is just from the top of my head, not something that should be used likely .. Or if using linux and have access to exec command I'd use awk
or sed
(better) to empty the file
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.
Try file_put_contents($filename, "");
or
unlink($filename);
touch($filename);
file_put_contents($file_name, "");
This is the best and simple option for clearing the contents of the file without deleting the file.
I don't know have you write the contents into the file, but if you use fopen
and you empty the file first, you are basically doing what the w
mode is doing anyway.
From the documentation:
'w': Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
So I really see no need in emptying it first as you probably will use the w
mode anyway.
You should only empty it if your code relies on the fact that this file is empty or if it is somehow security relevant.
You can't modify a file without opening it. The simplest way of doing that is to open it and truncate it while you open it, which in PHP would look like this:
fclose(fopen($filename, "w+"));
If you're going to invoke a unix shell (which is what the system() call does), the simplest way is to redirect /dev/null to the file, so in PHP that would be:
system(">$filename </dev/null");
There's a lot more overhead to this approach but it can be generalized and translated to any language or environment where you have a shell. There are other answers on this thread that have you calling system() to rm and then touch to recreate the file - besides being non-atomic, that approach also scares me much more.