Last updated on May 7th, 2025 at 09:05 am

Managing text files directly through a web interface can be incredibly useful for content updates, configuration changes, or simple data management tasks. With PHP, you can create a straightforward interface to view, edit, and save text files without needing FTP access or backend tools.

Prerequisites

Before proceeding, ensure:

  • PHP is Installed: Your server should have PHP installed and configured.
  • File Permissions: The text file you intend to edit should have appropriate read and write permissions.

Step-by-Step Guide

1. Create the PHP Script

Start by creating a PHP file, say edit_text_file.php, and add the following code:

<?php
$filename = "example.txt"; // Specify your text file

if (isset($_POST['content'])) {
    $content = stripslashes($_POST['content']);
    $file = fopen($filename, "w") or die("Unable to open file!");
    fwrite($file, $content);
    fclose($file);
    header("Location: edit_text_file.php");
    exit();
}
?>

2. Add the HTML Form

Below the PHP code, add the HTML form to display and edit the file content:

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
    <textarea name="content" rows="20" cols="80"><?php echo htmlspecialchars(file_get_contents($filename)); ?></textarea><br>
    <input type="submit" value="Save Changes">
</form>

This form displays the current content of the text file in a textarea, allowing you to make edits and save them.

Security Considerations

  • Input Validation: Always validate and sanitize user inputs to prevent malicious code execution.
  • File Access Control: Ensure that only authorized users can access and modify the text files.
  • Backup Files: Maintain backups of your text files to prevent data loss.

Conclusion

By following this guide, you can create a simple web-based interface to manage text files using PHP. This approach is beneficial for lightweight content management systems, configuration file edits, or any scenario requiring direct text file manipulation through a browser.

Demo