w1coding.comAll tutorials

PHP File

PHP lessons
  1. Environment Setup
  2. Introduction
  3. Variables
  4. Basics
  5. Operators
  6. Control
  7. Loops
  8. Variables
  9. Functions
  10. Arrays
  11. Superglobal
  12. File
  13. Loops
  14. Date
  15. Loops
  16. Strings
  17. Error
  18. Class
  19. File
  20. Include
  21. Sessions
  22. Mysql
  23. Cookies
  24. Forms
  25. Cookies
  26. Regular
  27. Authenthication
  28. Fileupload
  29. Mvc
  30. Responsive

PHP File Handling

PHP allows you to read, write, and manipulate files on your server. Here are a few important functions:

Opening a File

To open a file, use the fopen() function:

      
        <?php
          $file = fopen("example.txt", "r");
          if ($file) {
            echo "File opened successfully.";
          } else {
            echo "Unable to open file.";
          }
        ?>
      
    

Reading from a File

To read the contents of a file, use fread():

      
        <?php
          $file = fopen("example.txt", "r");
          $content = fread($file, filesize("example.txt"));
          echo $content;
          fclose($file);
        ?>
      
    

Writing to a File

To write to a file, use fwrite():

      
        <?php
          $file = fopen("example.txt", "w");
          fwrite($file, "Hello, this is a test file.");
          fclose($file);
        ?>
      
    

Activity

Try It Yourself!

Create a script that opens a file, reads its contents, and writes new data to the file.

Quiz

Quick Quiz

  1. What function is used to open a file in PHP?
  2. How do you write to a file in PHP?

Answers: Use fopen() to open a file. Use fwrite() to write to a file.