When creating a website that tracks user login and logout events, recording these activities in a text file is a common practice. While implementing such a feature, a common issue developers face is appending new data to the text file without overwriting existing content.
To achieve both creating and appending to a text file in PHP, consider using the following code:
<code class="php">$txt = "user id date"; $myfile = file_put_contents('logs.txt', $txt . PHP_EOL, FILE_APPEND | LOCK_EX);</code>
file_put_contents(): This function is used to write data to a text file. It takes three parameters:
When multiple users attempt to access the text file simultaneously, such as during login or logout events, concurrency issues may arise. To mitigate this, the LOCK_EX flag ensures that only one process can access the file at a time. This prevents multiple users from corrupting the data by overwriting each other's changes.
The above is the detailed content of How Do You Append New Data to a Text File in PHP Without Overwriting Existing Content?. For more information, please follow other related articles on the PHP Chinese website!