Skip to content
Alex Kiesel edited this page Jun 7, 2012 · 7 revisions

I/O: Basics

Files

The io.File class represents a file in the file system.

Reading a file

<?php
  with ($f= new File('/etc', 'passwd')); {
    $f->open(FILE_MODE_READ);
    while ($line= $f->readLine()) {
      // ...
    }
    $f->close();
  }
?>

Writing a file

<?php
  with ($f= new File('name.txt')); {
    $f->open(FILE_MODE_WRITE);
    $f->write('Timm'."\n");
    $f->close();
  }
?>

Appending a file

<?php
  with ($f= new File('names.txt')); {
    $f->open(FILE_MODE_APPEND);
    $f->write('Timm'."\n");
    $f->close();
  }
?>

FileUtil

Alternatively, the io.FileUtil class can be used to get and set the entire file contents at once:

<?php
  // Read words.txt's contents into a string
  $words= FileUtil::getContents(new File('words.txt'));
  
  // Write the string 'Timm' to a file called name.txt
  FileUtil::putContents(new File('name.txt'), 'Timm');
?>

Exceptions

All of the above methods will throw io.IOExceptions or subclasses of that on failure. So the above examples could be rewritten to handle errors gracefully as follows:

<?php
  try {
    $words= FileUtil::getContents(new File('words.txt'));
  } catch (FileNotFoundException $fe) {
    // File 'words.txt' was not found
  } catch (IOException $ie) {
    // Read error, permission denied
  }
?>

Folders

The io.Folder class represents a folder in the file system.

Iterating over a folder's contents

The following will yield all files and folders inside the /home folder except the well-known entries "." (current directory) and ".." (parent directory):

<?php
  $f= new Folder('/home/thekid');
  while ($e= $f->getEntry()) {
    // ... e= "bin" (directory, test with is_dir())
    // ... e= "bug12.patch" (file), test with is_file())
    // ... (etc.)
  }
?>

Note: The I/O Collections API offers a way more flexible approach!

Example: a temporary folder

This will create a folder named 'work' in the system's temporary directory and remove it once we're finished working with it.

<?php
  with ($work= new Folder(System::tempDir(), 'work')); {
    
    // Create only if it doesn't already exist yet.
    $work->exists() || $work->create();
  
    // ... work with the folder
  
    // Remove the folder and all of its contents recursively
    $work->unlink();
  }
?>