How to read and write part of a file

Modes used when opening a file with the fopen() function

Mode Description
'rb' Opens the file for reading. If the file doesn’t exist, fopen() returns FALSE.
'wb' Opens the file for writing. If the file exists, the existing data is deleted. If the file doesn’t exist, it is created.
'ab' Opens the file for writing. If the file exists, the new data is appended. If the file doesn’t exist, it is created.
'xb' Creates a new file for writing. If the file exists, fopen() returns FALSE.

Functions that open and close a file

Function Description
fopen($path, $mode) Opens the specified file with the specified mode and returns a file handle.
feof($file) Returns TRUE when the end of the specified file is reached.
fclose($file) Closes the specified file.

Functions that read from and write to a file

Function Description
fread($file, $length) Reads up to the specified number of bytes from the specified file.
fgets($file) Reads a line from the specified file.
fwrite($file, $data) Writes the specified string data to the specified file.

Read from a file

      $file = fopen('usernames.txt', 'rb'); 
      $names = "";
      while (!feof($file)) {
        $name = fgets($file);
        if ($name === false) {
          continue;
        }
        $name = trim($name); 
        if (strlen($name) == 0 || substr($name, 0, 1) == '#') {
          continue;
        }
        $names .= "<div>$name</div>";
      } 
      fclose($file);
      echo $names;
      

Write to a file

      $path = getcwd(); 
      $items = scandir($path); 
      $file = fopen('listing.txt', 'wb'); 
      foreach ($items as $item) {
        $item_path = $path . DIRECTORY_SEPARATOR . $item; 
        if (is_dir($item_path)) {
          fwrite($file, $item . "\n");
        } 
      } 
      fclose($file);
      

Back