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.

Basic usage

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

<?php
App::uses('Folder', 'Utility');
App::uses('File', 'Utility');

Then we can setup a new folder instance:

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

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

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

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

<?php
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, string|boolean $mode = false)
<?php
// Create a new folder with 0755 permissions
$dir = new Folder('/path/to/folder', true, 0755);
property Folder::$path

Path of the current 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(string $path, string $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

$element can also be an array:

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

New in version 2.5: $element parameter accepts an array as of 2.5

Folder::cd(string $path)
Return type:

string

Change directory to $path. Returns false on failure:

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

boolean

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

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

boolean

Copy a directory (recursively by default). The only parameter $options can either be a path into copy to or an array of options:

<?php
$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(array(
    'to' => '/path/to/new/folder',
    'from' => '/path/to/copy/from', // will cause a cd() to occur
    'mode' => 0755,
    'skip' => array('skip-me.php', '.git'),
    'scheme' => Folder::SKIP, // Skip directories/files that already exist.
    'recursive' => true //set false to disable recursive copy
));

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.

Changed in version 2.3: The merge, skip and overwrite schemes were added to copy()

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

string

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

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

boolean

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

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

boolean

Recursively remove directories if the system allows:

<?php
$folder = new Folder('foo');
if ($folder->delete()) {
    // Successfully deleted foo and its nested folders
}
Folder::dirsize()
Return type:

integer

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

Folder::errors()
Return type:

array

Get the error from latest method.

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

array

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

<?php
// Find all .png in your app/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()

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

array

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

<?php
// Recursively find files beginning with test or index
$dir = new Folder(WWW_ROOT);
$files = $dir->findRecursive('(test|index).*');
/*
Array
(
    [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(string $path = '')
Return type:

boolean

Returns true if the file is in a given CakePath.

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

boolean

Returns true if the file is in the given path:

<?php
$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(string $path)
Return type:

boolean

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

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

boolean

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

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

boolean

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

Folder::messages()
Return type:

array

Get the messages from the latest method.

Folder::move(array $options)
Return type:

boolean

Move a directory (recursively by default). The only parameter $options is the same as for copy()

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

string

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

Folder::pwd()
Return type:

string

Return current path.

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

mixed

Parameters:
  • $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 sub arrays: One of directories and one of files:

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

string

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

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

string

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

Folder::tree(null|string $path = null, array|boolean $exceptions = true, null|string $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 = 755)
<?php
// 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

The current file’s absolute path.

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

boolean

Append the given data string to the current file.

File::close()
Return type:

boolean

Closes the current file if it is opened.

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

boolean

Copy the file to $dest.

File::create()
Return type:

boolean

Creates the file.

File::delete()
Return type:

boolean

Deletes the file.

File::executable()
Return type:

boolean

Returns true if the file is executable.

File::exists()
Return type:

boolean

Returns true if the file exists.

File::ext()
Return type:

string

Returns the file extension.

File::Folder()
Return type:

Folder

Returns the current folder.

File::group()
Return type:

integer|false

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

File::info()
Return type:

array

Returns the file info.

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

File::lastAccess()
Return type:

integer|false

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

File::lastChange()
Return type:

integer|false

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

File::md5(integer|boolean $maxsize = 5)
Return type:

string

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

File::name()
Return type:

string

Returns the file name without extension.

File::offset(integer|boolean $offset = false, integer $seek = 0)
Return type:

mixed

Sets or gets the offset for the currently opened file.

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

boolean

Opens the current file with the given $mode.

File::owner()
Return type:

integer

Returns the file’s owner.

File::perms()
Return type:

string

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

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

string

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

File::pwd()
Return type:

string

Returns the full path of the file.

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

string|boolean

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

File::readable()
Return type:

boolean

Returns true if the file is readable.

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

string

Makes filename safe for saving.

File::size()
Return type:

integer

Returns the filesize.

File::writable()
Return type:

boolean

Returns true if the file is writable.

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

boolean

Write given data to the current file.

New in version 2.1: File::mime()

File::mime()
Return type:

mixed

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

File::replaceText($search, $replace)
Return type:

boolean

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

New in version 2.5: File::replaceText()