filesys / path
Help with handling or manipulating file and directory path.
Fund package maintenance!
Github
Patreon
Opencollective
Installs: 376
Dependents: 3
Suggesters: 0
Security: 0
Stars: 17
Watchers: 13
Forks: 13
Open Issues: 0
Requires
- php: ^7.2 || ^8.0
- web/url: ^1.0
README
PHP Path Help with handling or manipulating file and directory path.
Composer Installation
Installation is super-easy via Composer
composer require filesys/path
or add it by hand to your composer.json
file.
The Features of PHP Path
- Path::basename($path[, $suffix])
- Path::canonicalize($path)
- Path::changeExt($path, $newExt)
- Path::combine($paths, $names)
- Path::checkLength($path)
- Path::delimiter
- Path::dirname($path[, $suffix, $levels])
- Path::extname($path)
- Path::filename($path)
- Path::format($pathObject)
- Path::getcwd()
- Path::hasExt($path)
- Path::info()
- Path::isAbsolute($path)
- Path::isLocal($path)
- Path::isURIPath($path)
- Path::join([...$paths])
- Path::localBase($paths)
- Path::normalize($path)
- Path::optimize($path)
- Path::parse($path)
- Path::pathname($path)
- Path::pathToURL($path, $origin[, ?$query, ?$hash])
- Path::posix
- Path::relative($from, $to)
- Path::removeExt($path)
- Path::resolve(...$paths)
- Path::rootname($path)
- Path::sep
- Path::tmp($path)
- Path::toNamespacedPath($path)
- Path::UrlToPath($url)
- Path::win32
use Path\Path; require 'vendor/autoload.php';
Path::basename($path[, $suffix])
Parameters:
The Path::basename()
method returns the last portion of a path, similar to the Unix basename command. Trailing directory separators
are ignored.
For example, on POSIX:
Path::basename('C:\\xampp\\htdocs\\example.html'); // Returns: 'example.html' Path::basename('C:\\xampp\\htdocs\\example.html', '.html'); // Returns: 'example'
On Windows:
Path::basename('/home/local/user/example.html'); // Returns: 'example.html' Path::basename('/home/local/user/example.html', '.html'); // Returns: 'example'
Path::canonicalize($path)
Parameters:
canonicalize function converts a given path into its canonical (absolute and standardized) form. It resolves relative paths, symbolic links, and eliminates redundant or unnecessary components like '.' and '..' to return a clean and absolute version of the path.
For example, on POSIX:
Path::canonicalize('C:\\XamPP\\HtDocS\\DatA\\comPoseR.jSon'); // Returns: 'C:\\xampp\\htdocs\\data\\composer.json'
On Windows:
Path::canonicalize('/path/composer.json'); // Returns: 'G:\\path\\composer.json'
Path::changeExt($path, $newExt)
Parameters:
Returns a path string with changed initial extension to replaced new extension.
If path extension and givent new extension are same then changeExt will be not modify and return path with initial extension.
Path::changeExt('/foo/bar/baz/asdf/quux.html', '.php'); // Returns: '/foo/bar/baz/asdf/quux.php' Path::changeExt('/foo/bar/baz/asdf/vector.gif', 'svg'); // Returns: '/foo/bar/baz/asdf/vector.svg'
Path::combine($paths, $names)
Parameters:
Creates an array by using one array for paths and another for its names. And creates multiple files combined with paths from to file names.
For example, on POSIX:
Path::combine(['/xampp/htdocs'], ['example.html', 'foo.txt']); // Returns: ['/xampp/htdocs/example.html', '/xampp/htdocs/foo.txt'] Path::combine(['/xampp/htdocs'], ['example.html']); // Returns: ['/xampp/htdocs/example.html'] Path::combine(['/xampp/htdocs', '/path'], ['example.html']); // Returns: ['/xampp/htdocs/example.html', '/path/example.html'] Path::combine(['/xampp/htdocs', '/path'], ['example.html', 'foot.txt', '.env']); // Returns: ['/xampp/htdocs/example.html', '/xampp/htdocs/foot.txt', '/xampp/htdocs/.env', '\path\example.html', '\path\foot.txt', '\path\.env']
On Windows:
Path::combine(['C:\\xampp\\htdocs'], ['example.html', 'foo.txt']); // Returns: ['C:\\xampp\\htdocs\\example.html', 'C:\\xampp\\htdocs\\foo.txt'] Path::combine(['C:\\xampp\\htdocs'], ['example.html']); // Returns: ['C:\\xampp\\htdocs\\example.html'] Path::combine(['C:\\xampp\\htdocs', '\\path'], ['example.html']); // Returns: ['C:\\xampp\\htdocs\\example.html', '\\path\\example.html'] Path::combine(['C:\\xampp\\htdocs', '\\path'], ['example.html', 'foot.txt', '.env']); // Returns: ['C:\\xampp\\htdocs\\example.html', 'C:\\xampp\\htdocs\\foot.txt', 'C:\\xampp\\htdocs\\.env', '\\path\\example.html', '\\path\\foot.txt', '\\path\\.env']
Path::checkLength($path)
Parameters:
Check a valid path length and report exception.
// Check maximum path length on your system use \PHP_MAXPATHLEN constant. Path::checkLength('your-path'); // Returns: if given path of length are valid so return (void) otherwise throwing RTException Error. // PHP Fatal error: Uncaught Path\Exception\RTException: Invalid path because path length exceeds [2048] characters.
Throwing Error
Path\Exception\RTException: Invalid path because path length exceeds [2048] characters.
Path::delimiter
Provides the platform-specific path delimiter:
;
for Windows:
for POSIX
For example, on POSIX:
echo getenv('PATH'); // Prints: '/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin' explode(Path::delimiter, getenv('PATH')); // Returns: ['/usr/bin', '/bin', '/usr/sbin', '/sbin', '/usr/local/bin']
On Windows:
echo getenv('PATH'); // Prints: 'C:\Windows\system32;C:\Windows;C:\Program Files\node\' explode(Path::delimiter, getenv('PATH')); // Returns ['C:\\Windows\\system32', 'C:\\Windows', 'C:\\Program Files\\node\\']
Path::dirname($path[, $suffix, $levels])
Parameters:
Get the directory name of a given path with optional suffix removal and level adjustment. This function returns the parent directory's path of the provided file or directory path. It also allows for an optional suffix to be removed from the base name and specifies how many levels up the directory to go.
For example, on POSIX:
Path::dirname('/foo/bar/baz/asdf/quux\\abcd\\xyz'); // Returns: '/foo/bar/baz/asdf'
On Windows:
Path::dirname('/foo/bar/baz/asdf/quux'); // Returns: '/foo/bar/baz/asdf' Path::dirname('/foo/bar/baz/asdf/quux\\abcd\\xyz'); // Returns: '/foo/bar/baz/asdf/quux\abcd'
Path::extname($path)
Parameters:
Returns extname method a path extension name from given path, Its used to get file extention.
Path::extname('C:\\xampp\\htdocs\\example.html'); // Returns: '.html' Path::extname('index.coffee.md'); // Returns: '.md' Path::extname('index.'); // Returns: '.' Path::extname('index'); // Returns: '' Path::extname('.index'); // Returns: '.index' Path::extname('C:\\xampp\\htdocs\\example.md'); // Returns: '.md'
Path::filename($path)
Parameters:
Returns a filename without extention of given path.
Path::filename('/foo/bar/baz/asdf/quux.html'); // Returns: 'quux.html' Path::filename('example.txt'); Path::filename('/'); // Returns: '' // Returns: 'example.txt' Path::filename('example'); // Returns: 'example' Path::filename('C:\\path\\dir\\file.txt'); // Returns: 'file.txt'
Path::format($pathObject)
Parameters:
Returns a path string from an array-object - the opposite of parse(). format method are same work as phpinfo
method But there install the extra property root
property to getting current root [dir] of path
For example, on POSIX:
// If `dir`, `root` and `base` are provided, // `${dir}${Path::sep}${base}` // will be returned. `root` is ignored. Path::format([ 'root' => '/ignored', 'dir' => '/home/user/dir', 'base' => 'file.txt', ]); // Returns: '/home/user/dir/file.txt' // `root` will be used if `dir` is not specified. // If only `root` is provided or `dir` is equal to `root` then the // platform separator will not be included. `ext` will be ignored. Path::format([ 'root' => '/', 'base' => 'file.txt', 'ext' => 'ignored', ]); // Returns: '/file.txt' // `name` + `ext` will be used if `base` is not specified. Path::format([ 'root' => '/', 'name' => 'file', 'ext' => '.txt', ]); // Returns: '/file.txt' // The dot will be added if it is not specified in `ext`. Path::format([ 'root' => '/', 'name' => 'file', 'ext' => 'txt', ]); // Returns: '/file.txt'
On Windows:
Path::format([ 'dir' => 'C:\\path\\dir', 'base' => 'file.txt', ]); // Returns: 'C:\\path\\dir\\file.txt'
Path::getcwd()
Retrieves the current working directory based on the operating system. This method returns the current working directory in a format appropriate for the platform. For POSIX
systems, it returns a path like /xampp/htdocs/
, while for Windows systems, it returns a path like C:/xampp/htdocs/
.
For example, on POSIX:
// If the current working directory is /xampp/htdocs, Path::getcwd(); // Returns: /xampp/htdocs
On Windows:
// If the current working directory is C:\\xampp\\htdocs, // returns with drive LIKE (eg: C:,D:,F: etc.) Path::getcwd(); // Returns: C:\\xampp\\htdocs
Path::hasExt($path)
Parameters:
hasExt method will check extension exists or not exists of given path and matcher Extensions, if Given extensions in matched path extension then return true, Otherwise return false.
Path::hasExt('/foo/bar/baz/asdf/vector.png', ['.gif', '.jpg', '.png']); // Returns: true Path::hasExt('/foo/bar/baz/asdf/vector.gif', '.gif'); // Returns: true Path::hasExt('/foo/bar/baz/asdf/vector.gif', 'gif'); // Returns: true Path::hasExt('/foo/bar/baz/asdf/vector.gif', ['gif', 'jpeg', 'png']); // Returns: true Path::hasExt('/foo/bar/baz/asdf/vector.pdf', ['.gif', '.jpg', '.png']); // Returns: false Path::hasExt('/foo/bar/baz/asdf/vector.gif', '.svg'); // Returns: false Path::hasExt('/foo/bar/baz/asdf/vector.gif', 'png'); // Returns: false Path::hasExt('/foo/bar/baz/asdf/vector.gif', ['svg', 'jpeg', 'png']); // Returns: false
Path::info()
Returns information about a file path.
For example, on POSIX:
Path::info('/home/local/user/example.html'); // Returns: stdClass Object ( // [dirname] => /home/local/user // [basename] => example.html // [extension] => html // [filename] => example // [root] => / // )
On Windows:
Path::info('C:\\xampp\\htdocs\\path\\Path.php'); // Returns: stdClass Object ( // [dirname] => C:/xampp/htdocs/path // [basename] => Path.php // [extension] => php // [filename] => Path // [root] => C:\ // )
Path::isAbsolute($path)
Parameters:
Determines whether {path} is an absolute path. An absolute path will always resolve to the same location,regardless of the working directory.
For example, on POSIX:
Path::isAbsolute('/foo/bar'); // Returns: true Path::isAbsolute('/baz/..'); // Returns: true Path::isAbsolute('qux/'); // Returns: false Path::isAbsolute('.'); // Returns: false
On Windows:
Path::isAbsolute('//server'); // Returns: true Path::isAbsolute('\\\\server'); // Returns: true Path::isAbsolute('C:/foo/..'); // Returns: true Path::isAbsolute('C:\\foo\\..'); // Returns: true Path::isAbsolute('bar\\baz'); // Returns: false Path::isAbsolute('bar/baz'); // Returns: false Path::isAbsolute('.'); // Returns: false
Path::isLocal($path)
Parameters:
isLocal function checks whether the provided path is local or not. It determines if the given path refers to a local file or directory.
Path::isLocal('C:Users\JohnDoe\Documents\file.txt'); // Returns: 'false' Path::isLocal('//home/user/file.txt'); // Returns: 'false' Path::isLocal('C:\Program Files\file//file.txt'); // Returns: 'false' Path::isLocal('C:/Windows\\System32'); // Returns: 'false' Path::isLocal('D:\\Data\report.pdf'); // Returns: 'false' Path::isLocal('C:\Users\JohnDoe\Documents\file.txt'); // Returns: 'true' Path::isLocal('D:\Projects\Code\index.html'); // Returns: 'true' Path::isLocal('/home/user/documents/report.pdf'); // Returns: 'true' Path::isLocal('\\ServerName\SharedFolder\image.png'); // Returns: 'true' Path::isLocal('E:\Music\Rock\song.mp3'); // Returns: 'true'
Path::isURIPath($path)
Parameters:
Check if the given path is a valid network path. A valid network path starts with two backslashes \\
or //
followed by the server name, and can include subdirectories.
Support: working only Windows:
Path::isURIPath('//home/local/user/'); // Returns: true Path::isURIPath('//home/local'); // Returns: true Path::isURIPath('//home/local/'); // Returns: true Path::isURIPath('/server/foo/'); // Returns: false Path::isURIPath('D:/'); // Returns: false Path::isURIPath('//home/'); // Returns: false Path::isURIPath('C:/xampp/htdocs/'); // Returns: false
Path::join([...$paths])
Parameters:
Join all arguments together and normalize the resulting path.
Path::join('/foo', 'bar', 'baz/asdf', 'quux', '..'); // Returns: '/foo/bar/baz/asdf' Path::join('foo', [], 'bar'); // Throws TypeError: Path\Path::join(): Argument #2 must be of type string, array given.
Path::localBase($paths)
// Temporary Unavailable
Path::normalize($path)
Parameters:
Normalize a string path, reducing ..
and .
parts. When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used.
For example, on POSIX:
Path::normalize('/foo/bar//baz/asdf/quux/..'); // Returns: '/foo/bar/baz/asdf'
On Windows:
Path::normalize('C:\\temp\\\\foo\\bar\\..\\'); // Returns: 'C:\\temp\\foo\\'
Since Windows recognizes multiple path separators, both separators will be replaced by instances of the Windows preferred separator (\
):
Path::win32::normalize('C:////temp\\\\/\\/\\/foo/bar'); // Returns: 'C:\\temp\\foo\\bar'
Path::optimize($path)
Path::parse($path)
Parameters:
Returns an object from a path string - the opposite of format()
.
For example, on POSIX:
Path::parse('/home/user/dir/file.txt'); // Returns: // [ // 'root' => '/', // 'dir' => '/home/user/dir', // 'base' => 'file.txt', // 'ext' => '.txt', // 'name' => 'file' // ]
┌─────────────────────┬────────────┐
│ dir │ base │
├──────┬ ├──────┬─────┤
│ root │ │ name │ ext │
" / home/user/dir / file .txt "
└──────┴──────────────┴──────┴─────┘
(All spaces in the "" line should be ignored. They are purely for formatting.)
On Windows:
path.parse('C:\\path\\dir\\file.txt'); // Returns: // [ // 'root' => 'C:\\', // 'dir' => 'C:\\path\\dir', // 'base' => 'file.txt', // 'ext' => '.txt', // 'name' => 'file' // ]
┌─────────────────────┬────────────┐
│ dir │ base │
├──────┬ ├──────┬─────┤
│ root │ │ name │ ext │
" C:\ path\dir \ file .txt "
└──────┴──────────────┴──────┴─────┘
(All spaces in the "" line should be ignored. They are purely for formatting.)
Path::pathname($path)
Parameters:
Get the path name of a given file or directory. This function returns the path name without any suffix or modification and without drive.
For example, on POSIX:
Path::pathname('//var/www/httpdocs/config/config.yml'); // Returns: '/var/www/httpdocs/config/config.yml' Path::pathname('C:////temp\\\\/\\/\\/foo/bar'); // Returns: 'C:/temp\foo/bar' Path::pathname('/'); // Returns: '/' Path::pathname('/var/www/httpdocs/config/config.yml'); // Returns: '/var/www/httpdocs/config/config.yml'
On Windows:
// Handle Network Path, Here network path are '\\\\var\\www' Path::pathname('\\\\var\\www\\httpdocs\\config\\config.yml'); // Returns: '\\httpdocs\\config\\config.yml' Path::pathname('C:////temp\\\\/\\/\\/foo/bar'); // Returns: '\\temp\\foo\\bar' Path::pathname('\\var\\www\\httpdocs\\config\\config.yml'); // Returns: '\\var\\www\\httpdocs\\config\\config.yml' Path::pathname('\\\\var\\www\\'); // Returns: '\\' Path::pathname('C:'); // Returns: '' Path::pathname('C:\\'); // Returns: '\\' Path::pathname('\\\\var\\www'); // Returns: '' Path::pathname('G:var\\www\\httpdocs\\config\\config.yml'); // Returns: 'var\\www\\httpdocs\\config\\config.yml'
Since Windows recognizes multiple path separators, both separators will be replaced by instances of the Windows preferred separator (\
):
Path::pathToURL($path, $origin[, ?$query, ?$hash])
Parameters:
pathToURL - Convert path to url, Returns path to url combination with (e.g., path, origin, ?query, ?hash)
.
Notice: Don't use syntax Path::win32::pathToURL()
or Path::posix::pathToURL()
, This a common bugs. but don't worry we fix this bugs to next expected version [v10.2.0]
.
For example, on POSIX:
Path::pathToURL('server/auth/client', 'https://www.example.com', 'id=1'); // Returns: 'https://www.example.com/server/auth/client?id=1' Path::pathToURL('server/auth/client', 'https://www.example.com'); // Returns: 'https://www.example.com/server/auth/client' Path::pathToURL('server/auth/client', 'https://www.example.com', '?id=1', '#root'); // Returns: 'https://www.example.com/server/auth/client?id=1#root' Path::pathToURL('server/auth/client', 'https://www.example.com', '?id=1', 'root'); // Returns: 'https://www.example.com/server/auth/client?id=1#root'
On Windows:
Path::pathToURL('G:\\server\\auth\\client', 'https://www.example.com', 'id=1'); // Returns: 'https://www.example.com/server/auth/client?id=1' Path::pathToURL('G:\\server\\auth\\client', 'https://www.example.com'); // Returns: 'https://www.example.com/server/auth/client' Path::pathToURL('G:\\server\\auth\\client', 'https://www.example.com', '?id=1', '#root'); // Returns: 'https://www.example.com/server/auth/client?id=1#root' Path::pathToURL('G:\\server\\auth\\client', 'https://www.example.com', '?id=1', 'root'); // Returns: 'https://www.example.com/server/auth/client?id=1#root'
Path::posix
The Path::posix
property provides access to POSIX specific implementations of the Path
methods.
The API is accessible via Path\Path::posix
or Path\Linux\Linux::class
.
Path::relative($from, $to)
Parameters:
Solve the relative path from from
to to
based on the current working directory. At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve.
For example, on POSIX:
Path::relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb'); // Returns: '../../impl/bbb'
On Windows:
Path::relative('C:\\orandea\\test\\aaa', 'C:\\orandea\\impl\\bbb'); // Returns: '..\\..\\impl\\bbb'
Path::removeExt($path)
Parameters:
Returns a path string with removed path extension.
Path::removeExt('/var/www/web.php'); // Returns: '/var/www/web' Path::removeExt('.env.local'); // Returns: '.env' Path::removeExt('.html'); // Returns: '' bugs detected Path::removeExt('file.txt'); // Returns 'file' Path::removeExt('G:/path/.github'); // Returns: 'G:/path/' bugs detected
Path::resolve(...$path)
Parameters:
The right-most parameter is considered to
. Other parameters are considered an array of from
. Starting from leftmost from
parameter, resolves to
to an absolute path. If to
isn't already absolute, from
arguments are prepended in right to left order, until an absolute path is found. If after using all from
paths still no absolute path is found, the current working directory is used as well. The resulting path is normalized, and trailing slashes are removed unless the path gets resolved to the root directory.
For example, on POSIX:
Path::resolve('/foo/bar', './baz'); // Returns: '/foo/bar/baz' Path::resolve('/foo/bar', '/tmp/file/'); // Returns: '/tmp/file' Path::resolve('wwwroot', 'static_files/png/', '../gif/image.gif'); // If the current working directory is /home/myself/node, // this returns '/home/myself/node/wwwroot/static_files/gif/image.gif'
On Windows:
Path::resolve('/foo/bar', './baz'); // Returns: 'G:\\foo\\bar\\baz' Path::resolve('/foo/bar', '/tmp/file/'); // Returns: 'G:\\tmp\\file' Path::resolve('wwwroot', 'static_files/png/', '../gif/image.gif'); // If the current working directory is C:\\xampp\\htdocs/, // this returns 'C:\\xampp\\htdocs\\wwwroot\\static_files\\gif\\image.gif'
Path::rootname($path)
Parameters:
Retrieves the root name of the path. This method extracts the root component of a given path, which can be useful for determining the base directory or starting point for further path manipulations.
For example, on POSIX:
Path::rootname('C:\\xampp\\htdocs\\'); // Returns: '' Path::rootname('/var/ww/httpdocs'); // Returns: '/' Path::rootname('C:\\'); // Returns: '' Path::rootname('G:'); // Returns: '' Path::rootname('//var/www/httpdocs'); // Returns: '/'
On Windows:
Path::rootname('C:\\xampp\\htdocs\\'); // Returns: 'C:\\' Path::rootname('/var/ww/httpdocs'); // Returns: '\\' Path::rootname('C:\\'); // Returns: 'C:\\' Path::rootname('G:'); // Returns: 'G:' Path::rootname('//var/www/httpdocs'); // Returns: '\\\\var\\www\\'
Path::sep
For example, on POSIX:
explode(Path::sep, 'foo/bar/baz'); // Returns: ['foo', 'bar', 'baz']
On Windows:
explode(Path::sep, 'foo\\bar\\baz'); // Returns: ['foo', 'bar', 'baz']
On Windows, both the forward slash (/
) and backward slash (\
) are accepted as path segment separators; however, the Path
methods only add backward slashes (\
).
Path::tmp($path)
Parameters:
Returns tmp name, To make a tmp name with dirname of given path.
For example, on POSIX:
// Path::tmp suffix random tmp name in given path value. Path::tmp('foot/bar/baz'); // Returns: 'foot/bar/.!!/.!HyZq' // Returns: 'foot/bar/.!!/.!XTfs' // Returns: 'foot/bar/.!!/.!C80D'
On Windows:
// Path::tmp suffix random tmp name in given path value. Path::tmp('foot\\bar\\baz'); // Returns: 'foot\\bar\\.!!\\.!RBDZ' // Returns: 'foot\\bar\\.!!\\.!NPia' // Returns: 'foot\\bar\\.!!\\.!0Kbx'
Path::toNamespacedPath($path)
Parameters:
On Windows
systems only, returns an equivalent namespace-prefixed path for the given path. If path is not a string, path will be returned without modifications. This method is meaningful only on Windows system. On POSIX
systems, the method is non-operational and always returns path without modifications.
Path::toNamespacedPath('\\foo\\bar/baz\\asdfquux\\abcd\\xyz'); // Returns: '\\\\?\\G:\\foo\\bar\\baz\\asdfquux\\abcd\\xyz' Path::toNamespacedPath('//foo\\bar/baz\\asdfquux\\abcd\\xyz'); // Returns: '\\\\?\\UNC\\foo\\bar\\baz\\asdfquux\\abcd\\xyz'
Path::UrlToPath($url)
Parameters:
To convert url https://example.com/home/parent/current/path
to /home/parent/current/path
.
For example, on POSIX:
Path::UrlToPath('https://www.example.com/server/auth/client?id=1'); // Returns: 'G:\\server\\auth\\client' Path::UrlToPath('https://www.example.com/server/auth/client'); // Returns: 'G:\\server\\auth\\client' Path::UrlToPath('https://www.example.com/server/auth/client?id=1#root'); // Returns: 'G:\\server\\auth\\client'
On Windows:
Path::UrlToPath('https://www.example.com/server/auth/client?id=1'); // Returns: '/server/auth/client' Path::UrlToPath('https://www.example.com/server/auth/client'); // Returns: '/server/auth/client' Path::UrlToPath('https://www.example.com/server/auth/client?id=1#root'); // Returns: '/server/auth/client'
Path::win32
The Path::win32
property provides access to Windows specific implementations of the Path
methods.
The API is accessible via Path\Path::win32
or Path\Win32\Win32::class
.