Online Notepad


In this tutorial we will create a online notepad script, this will demonstrate how to open and write to a file in PHP.

1. Create a blank .txt file called notepad within the same directory as you will create the PHP script below.
    Make sure this file has permission to be wrote to.

2. Copy below and save it as notepad.php

notepad.php
  1. <?php
  2. $file = "notepad.txt"; // The .txt file to store content
  3.  
  4. if (isset($_POST['edit'])) { // Form submitted
  5. $content = stripslashes($_POST['edit']); // Remove slashes added by magic quotes, if any
  6. if (file_put_contents($file, $content) !== false) { // Write content to the file
  7. echo "<p>File updated successfully.</p>";
  8. } else {
  9. echo "<p>Error: Unable to update the file.</p>";
  10. }
  11. }
  12.  
  13. // Read the file content
  14. $fileContent = "";
  15. if (file_exists($file)) {
  16. $fileContent = file_get_contents($file); // Get file content
  17. if ($fileContent === false) {
  18. echo "<p>Error: Unable to read the file content.</p>";
  19. $fileContent = ""; // Fallback to an empty string
  20. }
  21. }
  22. ?>
  23.  
  24. <form method="post">
  25. <textarea cols="60" rows="20" name="edit"><?php echo htmlspecialchars($fileContent); ?></textarea><br>
  26. <input type="submit" value="Update">
  27. </form>
DanielXP's Avatar
Author:
Views:
5,032
Rating:
There are currently no comments for this tutorial, login or register to leave one.