How to save string entered in HTML form to text file

How to save string entered in HTML form to text file

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

How to Save String Entered in HTML Form to Text File

Saving user input from an HTML form directly into a text file is a common requirement for logging events, storing simple logs, or creating rudimentary data archives. While modern applications often rely on databases, there are scenarios where a flat text file is sufficient and preferred due to its simplicity and human readability. The core challenge lies not in the logic of saving data, but in correctly extracting values from the $_POST superglobal array and handling file I/O securely.

The primary pitfall in your approach involves unnecessary string manipulation. In your first attempt, you used var_export(). This function is designed to generate a valid PHP data structure (like an array or object) that can be re-evaluated by the interpreter. It adds quotes around strings and escapes internal characters. If your goal is simply to store "John - Doe" in a text file, wrapping it in quotes turns the content into 'John - Doe', which corrupts the intended data format. Similarly, casting a string variable back to itself with "$var_str3" is redundant.

The cleanest approach uses direct concatenation. The $_POST superglobal array holds the form data as strings immediately upon submission. You can join these fields using the dot operator (.) to create the final string you wish to save. This avoids any overhead or transformation issues associated with serialization functions.

Implementing File Append Logic

To persist this data, you need to open a file handle and write to it. The file_put_contents() function is often preferred for its brevity, but understanding the underlying flags is crucial. The second argument specifies how to handle existing files. Using the constant FILE_APPEND combined with LOCK_EX (for exclusive locking) ensures that concurrent requests do not overwrite each other's data or create corrupted lines if multiple users submit simultaneously.

Here is a refined implementation using file_put_contents:

<?php
// Ensure we are handling POST data
if (isset($_POST['field1']) && isset($_POST['field2'])) {
    
    // Construct the string directly without var_export
    $entry = $_POST['field1'] . ' - ' . $_POST['field2'];
    
    // Append to fields.txt. 
    // LOCK_EX prevents race conditions if multiple requests hit this file simultaneously.
    $filename = 'fields.txt';
    $result = file_put_contents($filename, $entry . PHP_EOL, FILE_APPEND | LOCK_EX);
    
    if ($result === false) {
        // Handle potential permission errors or disk full scenarios
        error_log("Failed to write to file: " . error_get_last()['message'] ?? 'Unknown error');
    }
}
?>

If you prefer the procedural style seen in your second example, fopen() remains a valid option. However, it is vital to close the file handle using fclose() immediately after writing to release system resources. Leaving files open can lead to memory leaks in long-running scripts and prevent other processes from accessing the file.

Security Considerations

When saving text to a file, you must consider where the file resides and who has access to it. By default, web server processes run with specific permissions (often www-data or apache). If your script attempts to write to a directory outside of the web root, you will encounter permission denied errors. Ensure the target directory exists and that the web server user has write permissions.

Furthermore, while storing raw text in a .txt file is safe for human consumption, it exposes data to potential tampering if the file is accessible via the URL. If this log file contains sensitive information, ensure it is located outside the public document root or restrict access via web server configuration (e.g., .htaccess rules).

For more complex applications requiring robust data persistence, security, and concurrency management, you might consider migrating away from flat files to a database solution. For developers looking to build such scalable solutions quickly without managing low-level file I/O or database setup, resources like the LaravelCompany platform offer insights into building secure, maintainable applications using modern frameworks.

Our network