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

<?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, write or 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, mixed $mode = false)
<?php
// 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:

<?php
$path = Folder::addPathElement('/a/path/for', 'testing');
// $path equals /a/path/for/testing
Folder::cd($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($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:

<?php
$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:

<?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')
));
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:

<?php
$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:

<?php
$folder = new Folder('foo');
if ($folder->delete()) {
    // Successfully deleted foo 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 error from latest method.

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

Returns an array of all matching files in 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($pattern = '.*', $sort = false)
Return type:array

Returns an array of all matching files in and below 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($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:

<?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($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):

<?php
$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.

Folder::messages()
Return type:array

Get messages from latest method.

Folder::move($options)
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.)

Folder::pwd()
Return type:string

Return current path.

Folder::read($sort = true, $exceptions = false, $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 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
        (
            [0] => css
            [1] => img
            [2] => js
        )
    [1] => Array
        (
            [0] => .htaccess
            [1] => favicon.ico
            [2] => test.php
        )
)
*/
Folder::realpath($path)
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)
<?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

Current file’s absolute path.

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

Append given data string to this File.

File::close()
Return type:boolean

Closes the current file if it is opened.

File::copy($dest, $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

Returns the File’s group.

File::info()
Return type:string

Returns the File info.

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

File::lastAccess()
Return type:integer

Returns last access time.

File::lastChange()
Return type:integer

Returns last modified time.

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

Get md5 Checksum of file with previous check of Filesize

File::name()
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

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($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”

File::pwd()
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.

File::readable()
Return type:boolean

Returns true if the File is readable.

File::safe($name = NULL, $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($data, $mode = 'w', $force = false)
Return type:boolean

Write given data to this File.

New in version 2.1: File::mime()

File::mime()
Return type:mixed

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