Folder & File

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

Deprecated since version 4.0: The File and Folder classes will be removed in 5.0. Use SPL classes like SplFileInfo or SplFileObject and iterator classes like RecursiveDirectoryIterator, RecursiveRegexIterator etc. instead.

Basic Usage

Ensure the classes are loaded:

use Cake\Filesystem\Folder;
use Cake\Filesystem\File;

Then we can setup a new folder instance:

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

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

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

Now we can loop through the files and read from or write/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 Cake\Filesystem\Folder(string $path = false, boolean $create = false, string|boolean $mode = false)
// Create a new folder with 0755 permissions
$dir = new Folder('/path/to/folder', true, 0755);
property Cake\Filesystem\Folder::$path

Path of the current folder. Folder::pwd() will return the same information.

property Cake\Filesystem\Folder::$sort

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

property Cake\Filesystem\Folder::$mode

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

static Cake\Filesystem\Folder::addPathElement(string $path, string $element)

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

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

$element can also be an array:

$path = Folder::addPathElement('/a/path/for', ['testing', 'another']);
// $path equals /a/path/for/testing/another
Cake\Filesystem\Folder::cd($path)

Change directory to $path. Returns false on failure:

$folder = new Folder('/foo');
echo $folder->path; // Prints /foo
$folder->cd('/bar');
echo $folder->path; // Prints /bar
$false = $folder->cd('/non-existent-folder');
Cake\Filesystem\Folder::chmod(string $path, integer $mode = false, boolean $recursive = true, array $exceptions = [])

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, ['skip_me.php']);
Cake\Filesystem\Folder::copy(string $to, array $options = [])

Recursively copy a directory. The parameter $to is the location to copy to. The $options an array of options:

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

$folder = new Folder('/path/to/folder');
$folder->copy('/path/to/new/folder', [
    'from' => '/path/to/copy/from', // Will cause a cd() to occur
    'mode' => 0755,
    'skip' => ['skip-me.php', '.git'],
    'scheme' => Folder::SKIP  // Skip directories/files that already exist.
]);

Available options:

  • from The directory to copy from, this will cause a cd() to occur, changing the results of pwd().

  • mode The mode to copy the files/directories with as integer, e.g. 0775.

  • skip Files/directories to skip.

  • scheme Folder::MERGE, Folder::OVERWRITE, Folder::SKIP

  • recursive Whether to copy recursively or not (default: true - recursive)

There are 3 supported schemes:

  • Folder::SKIP skip copying/moving files & directories that exist in the destination directory.

  • Folder::MERGE merge the source/destination directories. Files in the source directory will replace files in the target directory. Directory contents will be merged.

  • Folder::OVERWRITE overwrite existing files & directories in the target directory with those in the source directory. If both the target and destination contain the same subdirectory, the target directory’s contents will be removed and replaced with the source’s.

static Cake\Filesystem\Folder::correctSlashFor(string $path)

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

Cake\Filesystem\Folder::create(string $pathname, integer $mode = false)

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
}
Cake\Filesystem\Folder::delete(string $path = null)

Recursively remove directories if the system allows:

$folder = new Folder('foo');
if ($folder->delete()) {
    // Successfully deleted foo and its nested folders
}
Cake\Filesystem\Folder::dirsize()

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

Cake\Filesystem\Folder::errors()

Get the error from latest method.

Cake\Filesystem\Folder::find(string $regexpPattern = '.*', boolean $sort = false)

Returns an array of all matching files in the current directory:

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

Note

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()

Cake\Filesystem\Folder::findRecursive(string $pattern = '.*', boolean $sort = false)

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

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

Returns true if the file is in a given CakePath.

Cake\Filesystem\Folder::inPath(string $path = '', boolean $reverse = false)

Returns true if the file is in the given path:

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

$result = $Folder->inPath(WWW_ROOT . 'img' . DS, true);
// $result = true, /var/www/example/webroot/img/ is in /var/www/example/webroot/
static Cake\Filesystem\Folder::isAbsolute(string $path)

Returns true if the given $path is an absolute path.

static Cake\Filesystem\Folder::isSlashTerm(string $path)

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 Cake\Filesystem\Folder::isWindowsPath(string $path)

Returns true if the given $path is a Windows path.

Cake\Filesystem\Folder::messages()

Get the messages from the latest method.

Cake\Filesystem\Folder::move(array $options)

Recursive directory move.

static Cake\Filesystem\Folder::normalizeFullPath(string $path)

Returns a path with slashes normalized for the operating system.

Cake\Filesystem\Folder::pwd()

Return current path.

Cake\Filesystem\Folder::read(boolean $sort = true, array|boolean $exceptions = false, boolean $fullPath = false)

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

$dir = new Folder(WWW_ROOT);
$files = $dir->read(true, ['files', 'index.php']);
/*
Array
(
    [0] => Array // Folders
        (
            [0] => css
            [1] => img
            [2] => js
        )
    [1] => Array // Files
        (
            [0] => .htaccess
            [1] => favicon.ico
            [2] => test.php
        )
)
*/
Cake\Filesystem\Folder::realpath(string $path)

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

static Cake\Filesystem\Folder::slashTerm(string $path)

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

Cake\Filesystem\Folder::tree(null|string $path = null, array|boolean $exceptions = true, null|string $type = null)

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

File API

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

The Folder object of the file.

property Cake\Filesystem\File::$name

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

property Cake\Filesystem\File::$info

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

property Cake\Filesystem\File::$handle

Holds the file handler resource if the file is opened.

property Cake\Filesystem\File::$lock

Enable locking for file reading and writing.

property Cake\Filesystem\File::$path

The current file’s absolute path.

Cake\Filesystem\File::append(string $data, boolean $force = false)

Append the given data string to the current file.

Cake\Filesystem\File::close()

Closes the current file if it is opened.

Cake\Filesystem\File::copy(string $dest, boolean $overwrite = true)

Copy the file to the absolute path $dest.

Cake\Filesystem\File::create()

Creates the file.

Cake\Filesystem\File::delete()

Deletes the file.

Cake\Filesystem\File::executable()

Returns true if the file is executable.

Cake\Filesystem\File::exists()

Returns true if the file exists.

Cake\Filesystem\File::ext()

Returns the file extension.

Cake\Filesystem\File::Folder()

Returns the current folder.

Cake\Filesystem\File::group()

Returns the file’s group, or false in case of an error.

Cake\Filesystem\File::info()

Returns the file info.

Cake\Filesystem\File::lastAccess()

Returns last access time.

Cake\Filesystem\File::lastChange()

Returns last modified time, or false in case of an error.

Cake\Filesystem\File::md5(integer|boolean $maxsize = 5)

Get the MD5 Checksum of file with previous check of filesize, or false in case of an error.

Cake\Filesystem\File::name()

Returns the file name without extension.

Cake\Filesystem\File::offset(integer|boolean $offset = false, integer $seek = 0)

Sets or gets the offset for the currently opened file.

Cake\Filesystem\File::open(string $mode = 'r', boolean $force = false)

Opens the current file with the given $mode.

Cake\Filesystem\File::owner()

Returns the file’s owner.

Cake\Filesystem\File::perms()

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

static Cake\Filesystem\File::prepare(string $data, boolean $forceWindows = false)

Prepares a ascii string for writing. Converts line endings to the correct terminator for the current platform. For Windows “\r\n” will be used, “\n” for all other platforms.

Cake\Filesystem\File::pwd()

Returns the full path of the file.

Cake\Filesystem\File::read(string $bytes = false, string $mode = 'rb', boolean $force = false)

Return the contents of the current file as a string or return false on failure.

Cake\Filesystem\File::readable()

Returns true if the file is readable.

Cake\Filesystem\File::safe(string $name = null, string $ext = null)

Makes filename safe for saving.

Cake\Filesystem\File::size()

Returns the filesize in bytes.

Cake\Filesystem\File::writable()

Returns true if the file is writable.

Cake\Filesystem\File::write(string $data, string $mode = 'w', boolean$force = false)

Write given data to the current file.

Cake\Filesystem\File::mime()

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

Cake\Filesystem\File::replaceText($search, $replace)

Replaces text in a file. Returns false on failure and true on success.