Folder & File

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

Deprecated since version 4.0: The File and Folder classes will be removed in 5.0

Basic Usage

Ensure the classes are loaded:

  1. use Cake\Filesystem\Folder;
  2. use Cake\Filesystem\File;

Then we can setup a new folder instance:

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

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

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

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

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

Folder API

  • class Cake\Filesystem\Folder(string $path = false, boolean $create = false, string|boolean $mode = false)
  1. // Create a new folder with 0755 permissions
  2. $dir = new Folder('/path/to/folder', true, 0755);
  • property Cake\Filesystem\Folder::$path
  • Path of the current folder. Folder::pwd() will return the sameinformation.
  • 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 onWindows machines.
  • static Cake\Filesystem\Folder::addPathElement(string $path, string $element)
  • Returns $path with $element added, with correct slash in-between:
  1. $path = Folder::addPathElement('/a/path/for', 'testing');
  2. // $path equals /a/path/for/testing

$element can also be an array:

  1. $path = Folder::addPathElement('/a/path/for', ['testing', 'another']);
  2. // $path equals /a/path/for/testing/another
  • Cake\Filesystem\Folder::cd($path)
  • Change directory to $path. Returns false on failure:
  1. $folder = new Folder('/foo');
  2. echo $folder->path; // Prints /foo
  3. $folder->cd('/bar');
  4. echo $folder->path; // Prints /bar
  5. $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 includeschanging the mode on files as well:
  1. $dir = new Folder();
  2. $dir->chmod('/path/to/folder', 0755, true, ['skip_me.php']);
  • Cake\Filesystem\Folder::copy(array|string $options = [])
  • Recursively copy a directory. The only parameter $options can eitherbe a path into copy to or an array of options:
  1. $folder1 = new Folder('/path/to/folder1');
  2. $folder1->copy('/path/to/folder2');
  3. // Will put folder1 and all its contents into folder2
  4.  
  5. $folder = new Folder('/path/to/folder');
  6. $folder->copy([
  7. 'to' => '/path/to/new/folder',
  8. 'from' => '/path/to/copy/from', // Will cause a cd() to occur
  9. 'mode' => 0755,
  10. 'skip' => ['skip-me.php', '.git'],
  11. 'scheme' => Folder::SKIP // Skip directories/files that already exist.
  12. ]);

There are 3 supported schemes:

  • Folder::SKIP skip copying/moving files & directories that exist in thedestination directory.
  • Folder::MERGE merge the source/destination directories. Files in thesource directory will replace files in the target directory. Directorycontents will be merged.
  • Folder::OVERWRITE overwrite existing files & directories in the targetdirectory with those in the source directory. If both the target anddestination contain the same subdirectory, the target directory’s contentswill be removed and replaced with the source’s.
  • static Cake\Filesystem\Folder::correctSlashFor(string $path)
  • Returns a correct set of slashes for given $path (‘' forWindows paths and ‘/’ for other paths).
  • Cake\Filesystem\Folder::create(string $pathname, integer $mode = false)
  • Create a directory structure recursively. Can be used to createdeep path structures like /foo/bar/baz/shoe/horn:
  1. $folder = new Folder();
  2. if ($folder->create('foo' . DS . 'bar' . DS . 'baz' . DS . 'shoe' . DS . 'horn')) {
  3. // Successfully created the nested folders
  4. }
  • Cake\Filesystem\Folder::delete(string $path = null)
  • Recursively remove directories if the system allows:
  1. $folder = new Folder('foo');
  2. if ($folder->delete()) {
  3. // Successfully deleted foo and its nested folders
  4. }
  • 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:
  1. // Find all .png in your webroot/img/ folder and sort the results
  2. $dir = new Folder(WWW_ROOT . 'img');
  3. $files = $dir->find('.*\.png', true);
  4. /*
  5. Array
  6. (
  7. [0] => cake.icon.png
  8. [1] => test-error-icon.png
  9. [2] => test-fail-icon.png
  10. [3] => test-pass-icon.png
  11. [4] => test-skip-icon.png
  12. )
  13. */

Note

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

  • Cake\Filesystem\Folder::findRecursive(string $pattern = '.*', boolean $sort = false)
  • Returns an array of all matching files in and below the current directory:
  1. // Recursively find files beginning with test or index
  2. $dir = new Folder(WWW_ROOT);
  3. $files = $dir->findRecursive('(test|index).*');
  4. /*
  5. Array
  6. (
  7. [0] => /var/www/cake/webroot/index.php
  8. [1] => /var/www/cake/webroot/test.php
  9. [2] => /var/www/cake/webroot/img/test-skip-icon.png
  10. [3] => /var/www/cake/webroot/img/test-fail-icon.png
  11. [4] => /var/www/cake/webroot/img/test-error-icon.png
  12. [5] => /var/www/cake/webroot/img/test-pass-icon.png
  13. )
  14. */
  • 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:
  1. $Folder = new Folder(WWW_ROOT);
  2. $result = $Folder->inPath(APP);
  3. // $result = false, /var/www/example/src/ is not in /var/www/example/webroot/
  4.  
  5. $result = $Folder->inPath(WWW_ROOT . 'img' . DS, true);
  6. // $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):
  1. $result = Folder::isSlashTerm('/my/test/path');
  2. // $result = false
  3. $result = Folder::isSlashTerm('/my/test/path/');
  4. // $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. Thereturned array holds two sub arrays: One of directories and one of files:
  1. $dir = new Folder(WWW_ROOT);
  2. $files = $dir->read(true, ['files', 'index.php']);
  3. /*
  4. Array
  5. (
  6. [0] => Array // Folders
  7. (
  8. [0] => css
  9. [1] => img
  10. [2] => js
  11. )
  12. [1] => Array // Files
  13. (
  14. [0] => .htaccess
  15. [1] => favicon.ico
  16. [2] => test.php
  17. )
  18. )
  19. */
  • 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 forWindows 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)
  1. // Create a new file with 0644 permissions
  2. $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 fromFile::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 thecorrect 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.