file

File Handling in PHP

File Handling in PHP

PHP provides functions to open, read, write, and close files. You can use these functions to interact with files on the server.

Opening a File

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

      
        <?php
          $file = fopen("example.txt", "r"); // Opens the file in read mode
          if ($file) {
            echo "File opened successfully!";
          }
        ?>
      
    

Reading a File

To read a file, use fgets() or fread():

      
        <?php
          $file = fopen("example.txt", "r");
          while ($line = fgets($file)) {
            echo $line;
          }
          fclose($file);
        ?>
      
    

Writing to a File

To write to a file, use fwrite():

      
        <?php
          $file = fopen("example.txt", "w");
          fwrite($file, "This is some new text.");
          fclose($file);
        ?>
      
    

Activity

Try It Yourself!

Create a script that writes your name to a file called "name.txt" and then reads it back to you.

Quiz

Quick Quiz

  1. What function do you use to open a file in PHP?
  2. How do you read the contents of a file line by line?

Answers: You use fopen() to open a file. To read it line by line, use fgets().