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.
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
}
<?php
// Create a new folder with 0755 permissions
$dir = new Folder('/path/to/folder', true, 0755);
Path of the current folder. Folder::pwd()
will return the same
information.
Whether or not the list results should be sorted by name.
Mode to be used when creating folders. Defaults to 0755
. Does nothing on
Windows machines.
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
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');
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'));
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()
string
Returns a correct set of slashes for given $path (’\’ for Windows paths and ‘/’ for other paths).
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
}
boolean
Recursively remove directories if the system allows:
<?php
$folder = new Folder('foo');
if ($folder->delete()) {
// Successfully deleted foo and its nested folders
}
integer
Returns the size in bytes of this Folder and its contents.
array
Get the error from latest method.
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()
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
)
*/
boolean
Returns true if the file is in a given CakePath.
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/
boolean
Returns true if the given $path is an absolute path.
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
boolean
Returns true if the given $path is a Windows path.
array
Get the messages from the latest method.
boolean
Move a directory (recursively by default). The only parameter $options is the same as for copy()
string
Returns a correct set of slashes for given $path (’\’ for Windows paths and ‘/’ for other paths).
string
Return current path.
mixed
$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
)
)
*/
string
Get the real path (taking “..” and such into account).
string
Returns $path with added terminating slash (corrected for Windows or other OS).
mixed
Returns an array of nested directories and files in each directory.
<?php
// Create a new file with 0644 permissions
$file = new File('/path/to/file.php', true, 0644);
The Folder object of the file.
The name of the file with the extension. Differs from
File::name()
which returns the name without the extension.
An array of file info. Use File::info()
instead.
Holds the file handler resource if the file is opened.
Enable locking for file reading and writing.
The current file’s absolute path.
boolean
Append the given data string to the current file.
boolean
Closes the current file if it is opened.
boolean
Copy the file to $dest.
boolean
Creates the file.
boolean
Deletes the file.
boolean
Returns true if the file is executable.
boolean
Returns true if the file exists.
string
Returns the file extension.
integer|false
Returns the file’s group, or false in case of an error.
array
Returns the file info.
Changed in version 2.1: File::info()
now includes filesize & mimetype information.
integer|false
Returns last access time, or false in case of an error.
integer|false
Returns last modified time, or false in case of an error.
string
Get the MD5 Checksum of file with previous check of filesize, or false in case of an error.
string
Returns the file name without extension.
mixed
Sets or gets the offset for the currently opened file.
boolean
Opens the current file with the given $mode.
integer
Returns the file’s owner.
string
Returns the “chmod” (permissions) of the file.
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.
string
Returns the full path of the file.
string|boolean
Return the contents of the current file as a string or return false on failure.
boolean
Returns true if the file is readable.
string
Makes filename safe for saving.
integer
Returns the filesize.
boolean
Returns true if the file is writable.
boolean
Write given data to the current file.
New in version 2.1: File::mime()
mixed
Get the file’s mimetype, returns false on failure.
boolean
Replaces text in a file. Returns false on failure and true on success.
New in version 2.5: File::replaceText()