How to Create or Append Text to a File
You are attempting to create or append to a text file named "logs.txt" every time a user logs in or out of your website. However, your current code is experiencing issues with appending data or creating the file if it doesn't exist.
Your original code uses the "wr" mode for opening the file, which opens it for writing and truncates the file to zero length. To append data, you should instead use the "a" mode, which opens the file for writing and appending to the end of the file.
Additionally, your code is prone to race conditions if multiple users try to access the file simultaneously. To prevent this, you can use the LOCK_EX flag in conjunction with FILE_APPEND. This will acquire an exclusive lock on the file, ensuring that only one process can write to it at a time.
Here's an improved version of your code that addresses these issues:
<code class="php">$txt = "user id date"; $myfile = file_put_contents('logs.txt', $txt.PHP_EOL, FILE_APPEND | LOCK_EX);</code>
This code will create or open the "logs.txt" file in append mode, ensuring that the new data is appended to the end of the file. It also acquires an exclusive lock on the file while writing, preventing multiple users from writing to the file simultaneously.
The above is the detailed content of How to Safely Append Text to a File in PHP?. For more information, please follow other related articles on the PHP Chinese website!