Filesystem Functions

Nette\Utils\FileSystem is a class with useful functions for working with the file system. One advantage over native PHP functions is that they throw exceptions in case of errors.

If you need to search for files on the disk, use Finder.

Installation:

composer require nette/utils

The following examples assume the following class alias is defined:

use Nette\Utils\FileSystem;

Manipulation

copy (string $origin, string $target, bool $overwrite=true)void

Copies a file or an entire directory. Overwrites existing files and directories by default. If $overwrite is set to false and the target file or directory $target already exists, it throws a Nette\InvalidStateException. Throws a Nette\IOException on error.

FileSystem::copy('/path/to/source', '/path/to/dest', overwrite: true);

createDir (string $directory, int $mode=0777)void

Creates a directory if it does not exist, including parent directories. Throws a Nette\IOException on error.

FileSystem::createDir('/path/to/dir');

delete (string $path): void

Deletes a file or an entire directory if it exists. If the directory is not empty, it deletes its contents first. Throws a Nette\IOException on error.

FileSystem::delete('/path/to/fileOrDir');

makeWritable (string $path, int $dirMode=0777, int $fileMode=0666)void

Sets file permissions to $fileMode or directory permissions to $dirMode. Recursively traverses and sets permissions for the entire directory content as well.

FileSystem::makeWritable('/path/to/fileOrDir');

open (string $path, string $mode): resource

Opens a file and returns a resource handle. The $mode parameter works the same as the native fopen() function. Throws a Nette\IOException on error.

$res = FileSystem::open('/path/to/file', 'r');

read (string $file): string

Reads the content of a file $file. Throws a Nette\IOException on error.

$content = FileSystem::read('/path/to/file');

readLines (string $file, bool $stripNewLines=true): \Generator

Reads the file content line by line. Unlike the native file() function, it does not load the entire file into memory but reads it continuously, allowing you to read files larger than the available memory. $stripNewLines specifies whether to remove the line break characters \r and \n. Throws a Nette\IOException on error.

$lines = FileSystem::readLines('/path/to/file');

foreach ($lines as $lineNum => $line) {
	echo "Line $lineNum: $line\n";
}

rename (string $origin, string $target, bool $overwrite=true)void

Renames or moves a file or directory specified by $origin to $target. Overwrites existing files and directories by default. If $overwrite is set to false and the target file or directory $target already exists, it throws a Nette\InvalidStateException. Throws a Nette\IOException on error.

FileSystem::rename('/path/to/source', '/path/to/dest', overwrite: true);

write (string $file, string $content, int $mode=0666)void

Writes the string $content to the file $file. Throws a Nette\IOException on error.

FileSystem::write('/path/to/file', $content);

Paths

isAbsolute (string $path)bool

Determines if the path $path is absolute.

FileSystem::isAbsolute('../backup'); // false
FileSystem::isAbsolute('/backup');   // true
FileSystem::isAbsolute('C:/backup'); // true

joinPaths (string …$segments)string

Joins all path segments and normalizes the result.

FileSystem::joinPaths('a', 'b', 'file.txt'); // 'a/b/file.txt'
FileSystem::joinPaths('/a/', '/b/');         // '/a/b/'
FileSystem::joinPaths('/a/', '/../b');       // '/b'

normalizePath (string $path)string

Normalizes .., ., and directory separators in the path to the system's standard.

FileSystem::normalizePath('/file/.');        // '/file/'
FileSystem::normalizePath('\file\..');       // '/file'
FileSystem::normalizePath('/file/../..');    // '/..'
FileSystem::normalizePath('file/../../bar'); // '/../bar'

unixSlashes (string $path)string

Converts slashes to / used on Unix systems.

$path = FileSystem::unixSlashes($path);

platformSlashes (string $path)string

Converts slashes to characters specific to the current platform, i.e., \ on Windows and / elsewhere.

$path = FileSystem::platformSlashes($path);

resolvePath (string $basePath, string $path)string

Resolves the final path from $path relative to the base directory $basePath. Absolute paths (/foo, C:/foo) remain unchanged (only normalizes slashes), relative paths are appended to the base path.

// On Windows, slashes in the output would be reversed (\)
FileSystem::resolvePath('/base/dir', '/abs/path');      // '/abs/path'
FileSystem::resolvePath('/base/dir', 'rel');            // '/base/dir/rel'
FileSystem::resolvePath('base/dir', '../file.txt');     // 'base/file.txt'
FileSystem::resolvePath('base', '');                    // 'base'

Static vs Non-static Approach

To easily replace the class with another one (e.g., a mock) for testing purposes, use it non-statically:

class AnyClassUsingFileSystem
{
	public function __construct(
		private FileSystem $fileSystem,
	) {
	}

	public function readConfig(): string
	{
		return $this->fileSystem->read(/* ... */);
	}

	...
}
version: 4.0 3.x 2.x