Can php clear file contents?

藏色散人
Release: 2023-03-09 13:34:01
Original
2084 people have browsed it

php can clear the file contents. The implementation method is: first create a PHP sample file; then open the file through "fopen($path, "r ");"; finally through "if( flock($fh , LOCK_EX) ){...}" to clear the file contents.

Can php clear file contents?

The operating environment of this article: windows7 system, PHP7.1 version, DELL G3 computer

Specific questions:

php clear file contents?

How to clear the contents of a file in php without using fopen($file, 'w ').

My requirement is this. I want to ensure that all the last content after writing the file is deleted. If I overwrite it directly, it will only cover the content I wrote this time. If the old content is longer than the new content, then it will The rest, and the PHP program needs to run 24 hours a day, and the operating efficiency must be ensured. I tried the fopen() method, and found that a lot of time was wasted when closing and opening file resources. I tested turning on the file lock on my local machine. Every time you use fopen() to clear a file, it can only be executed 5,000 times per second. If you only read and write, it can be executed nearly 200,000 times per second, so I would like to ask if there are other methods. achieve this purpose.

The implementation code is as follows:

$fh = fopen($path, "r+");
if( flock($fh, LOCK_EX) ){//加写锁
$old_content=json_decode(fread($fh,filesize($path)),true);
$old_content=$old_content.$new_content;
ftruncate($fh,0); // 将文件截断到给定的长度
rewind($fh); // 倒回文件指针的位置
fwrite($fh,json_encode($old_content));
// @chmod($path,0644);
flock($fh, LOCK_UN); //解锁
}
fclose($fh);
Copy after login

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of Can php clear file contents?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template