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

前端 未结 6 1792
面向向阳花
面向向阳花 2020-12-07 03:20

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

6条回答
  •  抹茶落季
    2020-12-07 03:54

    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 

    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.

提交回复
热议问题