Page contents

Folder & File

The Folder and File utilities are convenience classes to help you read, write, and append to files; list files within a folder and other common directory related tasks.

Basic usage

Ensure the classes are loaded using App::uses():

App::uses('Folder', 'Utility');
App::uses('File', 'Utility');

Then we can setup a new folder instance:

$dir = new Folder('/path/to/folder');

and search for all .ctp files within that folder using regex:

$files = $dir->find('.*\.ctp');

Now we can loop through the files and read, write or append to the contents or simply delete the file:

foreach ($files as $file) {
    $file = new File($dir->pwd() . DS . $file);
    $contents = $file->read();
    // $file->write('I am overwriting the contents of this file');
    // $file->append('I am adding to the bottom of this file.');
    // $file->delete(); // I am deleting this file
    $file->close(); // Be sure to close the file when you're done

Folder API

class Folder(string $path = false, boolean $create = false, mixed $mode = false)
// Create a new folder with 0755 permissions
$dir = new Folder('/path/to/folder', true, 0755);
property Folder::$path

Current path to the folder. Folder::pwd() will return the same information.

property Folder::$sort

Whether or not the list results should be sorted by name.

property Folder::$mode

Mode to be used when creating folders. Defaults to 0755. Does nothing on windows machines.

static Folder::addPathElement($path, $element)
Return type:string

Returns $path with $element added, with correct slash in-between:

$path = Folder::addPathElement('/a/path/for', 'testing');
// $path equals /a/path/for/testing
Return type:string

Change directory to $path. Returns false on failure:

$folder = new Folder('/foo');
echo $folder->path; // Prints /foo
echo $folder->path; // Prints /bar
$false = $folder->cd('/non-existent-folder');
Folder::chmod($path, $mode = false, $recursive = true, $exceptions = array ( ))
Return type:boolean

Change the mode on a directory structure recursively. This includes changing the mode on files as well:

$dir = new Folder();
$dir->chmod('/path/to/folder', 0755, true, array('skip_me.php'));
Folder::copy($options = array ( ))
Return type:boolean

Recursively copy a directory. The only parameter $options can either be a path into copy to or an array of options:

$folder1 = new Folder('/path/to/folder1');
// Will put folder1 and all its contents into folder2

$folder = new Folder('/path/to/folder');
    'to' => '/path/to/new/folder',
    'from' => '/path/to/copy/from', // will cause a cd() to occur
    'mode' => 0755,
    'skip' => array('skip-me.php', '.git')
static Folder::correctSlashFor($path)
Return type:string

Returns a correct set of slashes for given $path. (\ for Windows paths and / for other paths.)

Folder::create($pathname, $mode = false)
Return type:boolean

Create a directory structure recursively. Can be used to create deep path structures like /foo/bar/baz/shoe/horn:

$folder = new Folder();
if ($folder->create('foo' . DS . 'bar' . DS . 'baz' . DS . 'shoe' . DS . 'horn')) {
    // Successfully created the nested folders
Folder::delete($path = NULL)
Return type:boolean

Recursively remove directories if the system allows:

$folder = new Folder('foo');
if ($folder->delete()) {
    // Successfully deleted foo its nested folders
Return type:integer

Returns the size in bytes of this Folder and its contents.

Return type:array

Get error from latest method.

Folder::find($regexpPattern = '.*', $sort = false)
Return type:array

Returns an array of all matching files in current directory:

// Find all .png in your app/webroot/img/ folder and sort the results
$dir = new Folder(WWW_ROOT . 'img');
$files = $dir->find('.*\.png', true);
    [0] => cake.icon.png
    [1] => test-error-icon.png
    [2] => test-fail-icon.png
    [3] => test-pass-icon.png
    [4] => test-skip-icon.png


The folder find and findRecursive methods will only find files. If you would like to get folders and files see Folder::read() or Folder::tree()

Folder::findRecursive($pattern = '.*', $sort = false)
Return type:array

Returns an array of all matching files in and below current directory:

// Recursively find files beginning with test or index
$dir = new Folder(WWW_ROOT);
$files = $dir->findRecursive('(test|index).*');
    [0] => /var/www/cake/app/webroot/index.php
    [1] => /var/www/cake/app/webroot/test.php
    [2] => /var/www/cake/app/webroot/img/test-skip-icon.png
    [3] => /var/www/cake/app/webroot/img/test-fail-icon.png
    [4] => /var/www/cake/app/webroot/img/test-error-icon.png
    [5] => /var/www/cake/app/webroot/img/test-pass-icon.png
Folder::inCakePath($path = '')
Return type:boolean

Returns true if the File is in a given CakePath.

Folder::inPath($path = '', $reverse = false)
Return type:boolean

Returns true if the File is in given path:

$Folder = new Folder(WWW_ROOT);
$result = $Folder->inPath(APP);
// $result = true, /var/www/example/app/ is in /var/www/example/app/webroot/

$result = $Folder->inPath(WWW_ROOT . 'img' . DS, true);
// $result = true, /var/www/example/app/webroot/ is in /var/www/example/app/webroot/img/
static Folder::isAbsolute($path)
Return type:boolean

Returns true if given $path is an absolute path.

static Folder::isSlashTerm($path)
Return type:boolean

Returns true if given $path ends in a slash (i.e. is slash-terminated):

$result = Folder::isSlashTerm('/my/test/path');
// $result = false
$result = Folder::isSlashTerm('/my/test/path/');
// $result = true
static Folder::isWindowsPath($path)
Return type:boolean

Returns true if given $path is a Windows path.

Return type:array

Get messages from latest method.

Return type:boolean

Recursive directory move.

static Folder::normalizePath($path)
Return type:string

Returns a correct set of slashes for given $path. (\ for Windows paths and / for other paths.)

Return type:string

Return current path.

Folder::read($sort = true, $exceptions = false, $fullPath = false)
Return type:


  • $sort (boolean) – If true will sort results.
  • $exceptions (mixed) – An array of files and folder names to ignore. If true or ‘.’ this method will ignore hidden or dot files.
  • $fullPath (boolean) – If true will return results using absolute paths.

Returns an array of the contents of the current directory. The returned array holds two arrays: One of directories and one of files:

$dir = new Folder(WWW_ROOT);
$files = $dir->read(true, array('files', 'index.php'));
    [0] => Array
            [0] => css
            [1] => img
            [2] => js
    [1] => Array
            [0] => .htaccess
            [1] => favicon.ico
            [2] => test.php
Return type:string

Get the real path (taking ”..” and such into account).

static Folder::slashTerm($path)
Return type:string

Returns $path with added terminating slash (corrected for Windows or other OS).

Folder::tree($path = NULL, $exceptions = true, $type = NULL)
Return type:mixed

Returns an array of nested directories and files in each directory.

File API

class File(string $path, boolean $create = false, integer $mode = 493)
// Create a new file with 0644 permissions
$file = new File('/path/to/file.php', true, 0644);
property File::$Folder

The Folder object of the file.

property File::$name

The name of the file with the extension. Differs from File::name() which returns the name without the extension.

property File::$info

An array of file info. Use File::info() instead.

property File::$handle

Holds the file handler resource if the file is opened.

property File::$lock

Enable locking for file reading and writing.

property File::$path

Current file’s absolute path.

File::append($data, $force = false)
Return type:boolean

Append given data string to this File.

Return type:boolean

Closes the current file if it is opened.

File::copy($dest, $overwrite = true)
Return type:boolean

Copy the File to $dest

Return type:boolean

Creates the File.

Return type:boolean

Deletes the File.

Return type:boolean

Returns true if the File is executable.

Return type:boolean

Returns true if the File exists.

Return type:string

Returns the File extension.

Return type:Folder

Returns the current folder.

Return type:integer

Returns the File’s group.

Return type:string

Returns the File info.

Changed in version 2.1: File::info() now includes filesize & mimetype information.

Return type:integer

Returns last access time.

Return type:integer

Returns last modified time.

File::md5($maxsize = 5)
Return type:string

Get md5 Checksum of file with previous check of Filesize

Return type:string

Returns the File name without extension.

File::offset($offset = false, $seek = 0)
Return type:mixed

Sets or gets the offset for the currently opened file.

File::open($mode = 'r', $force = false)
Return type:boolean

Opens the current file with a given $mode

Return type:integer

Returns the File’s owner.

Return type:string

Returns the “chmod” (permissions) of the File.

static File::prepare($data, $forceWindows = false)
Return type:string

Prepares a ascii string for writing. Converts line endings to the correct terminator for the current platform. If windows “rn” will be used all other platforms will use “n”

Return type:string

Returns the full path of the File.

File::read($bytes = false, $mode = 'rb', $force = false)
Return type:mixed

Return the contents of this File as a string or return false on failure.

Return type:boolean

Returns true if the File is readable.

File::safe($name = NULL, $ext = NULL)
Return type:string

Makes filename safe for saving.

Return type:integer

Returns the Filesize.

Return type:boolean

Returns true if the File is writable.

File::write($data, $mode = 'w', $force = false)
Return type:boolean

Write given data to this File.

New in version 2.1: File::mime()

Return type:mixed

Get the file’s mimetype, returns false on failure.