PHP write file from input to txt
When you attempt to persist form data directly into a text file, it is easy to fall into the trap of managing state incorrectly or mishandling file handles. A common scenario involves a simple HTML form submitting fields like field1 and field2, followed by a PHP script intended to log these values to data.txt. If the result is a blank page where the download link should be, or if the file remains empty despite execution, the issue usually lies in how the script handles the request lifecycle and file I/O.
In the provided example, the PHP code checks for POST data using isset($_POST['field1']) and isset($_POST['field2']). If both exist, the script constructs a string and attempts to write it. However, there is a critical logical flaw in the flow: the file_put_contents() function is called immediately after the condition check. This function returns the number of bytes written or false on failure. Crucially, if the file does not exist yet, file_put_contents creates it. But looking closer at the code structure, there is a redundant and potentially blocking operation involving the $fh file handle that was opened with fopen($txt, 'w+').
The script opens the file for reading and writing in update mode ('w+'). The 'w' portion truncates the file to zero length if it already exists. If the intention is to append, 'a' should be used instead. However, the most significant issue in the provided snippet is the presence of file_put_contents('data.txt', $txt."\n", FILE_APPEND) followed by an exit() call. The exit() statement terminates the script immediately after writing via file_put_contents. This means the subsequent block:
fwrite($fh, $txt);
fclose($fh);
is never reached. You cannot write to a file handle $fh if the script has already exited and you just performed a different write operation that didn't explicitly close that handle first. Furthermore, opening a file with 'w+' truncates it every time the script runs. If you want to accumulate logs over multiple requests, you must use 'a' (append) or ensure the truncation is intentional.
The exit() call inside the if block prevents any output from being generated after the write operation. While this might seem intentional to prevent further processing, it also means that if you intended to display a success message or redirect the user, that code will never run. If the goal is simply to save the file and allow the page to load (perhaps showing a link to download data.txt), removing the exit() call is necessary. Without it, the browser might interpret the lack of HTML output as an error if the script was expected to render a response.
Consider the flow:
- File Handle Management: Opening a file with
fopen()returns a resource. If you do not close this resource before exiting or finishing execution, you risk holding a file lock, preventing other processes from writing to it. In the original code,$fhis opened but never closed because of the early exit. - File Mode: Using
'w+'deletes existing content every time. Ifdata.txtcontains history, this mode wipes it clean. Switching to'a'preserves previous entries while adding new ones. - Output Handling: If the script is executed via a web server (Apache/Nginx + PHP-FPM), standard output goes to the browser unless redirected. If you want to serve an HTML page after writing the file, you must ensure no
exit()prevents the rendering of that HTML.
A corrected approach would remove the unused file handle logic if relying on file_put_contents, which is generally preferred for its simplicity and atomicity in single writes. It handles creation implicitly and manages buffers internally. If using fopen(), ensure you close the handle explicitly:
<?php
$txt = "data.txt";
$fh = fopen($txt, 'a'); // Use 'a' to append, not 'w+' which truncates
if (isset($_POST['field1']) && isset($_POST['field2'])) {
$content = $_POST['field1'] . ' - ' . $_POST['field2'] . "\n";
fwrite($fh, $content);
fclose($fh); // Always close the handle
// Do not exit here if you need to send HTML back
}
// Continue with any other logic or output generation
?>
This ensures the file is updated correctly and that subsequent code can execute. Additionally, always consider permissions; writing to data.txt requires the web server user (often www-data or nginx) to have write permissions on that directory. Without them, you will see a "Permission denied" error in your logs rather than a blank file.
For developers moving from raw PHP to frameworks like Laravel, this logic is abstracted into service classes or event listeners, but the underlying principles of file modes and handle management remain identical. If you are looking for a more robust way to handle file operations within a larger application architecture, resources like https://laravelcompany.com discuss how frameworks manage storage drivers and file locking to prevent race conditions during concurrent writes.
