PHP code example of code-distortion / path

1. Go to this page and download the library: Download code-distortion/path library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

code-distortion / path example snippets


Use CodeDistortion\Path\Path;

$path = Path::new('/path/to/file.txt');

(string) $path;             // '/path/to/file.txt' (castable to a string)
$path->getDir();            // '/path/to/' (the dir as a new Path object)
$path->getFilename();       // 'file.txt'
$path->getFilename(false);  // 'file'
$path->getExtension();      // '.txt'
$path->getExtension(false); // 'txt'
$path->isAbsolute();        // true
$path->isRelative();        // false

// dir paths
Path::new('/path/to/thing/');   // '/path/to/thing/'
Path::newDir('/path/to/thing'); // '/path/to/thing/' (enforces that it's a dir)
// file paths
Path::new('/path/to/thing');      // '/path/to/thing'
Path::newFile('/path/to/thing/'); // '/path/to/thing' (enforces that it's a file)

Path::new('/a//b/.././c')->resolve(); // '/a/c' - removes unnecessary parts

Path::newDir('/path/to/uploads/')->add('my-file.txt');           // '/path/to/uploads/my-file.txt'
// make sure that your file doesn't break out from the base
Path::newDir('/path/to/uploads/')->add('../my-file.txt');        // '/path/to/uploads/my-file.txt'
// or allow it to break out
Path::newDir('/path/to/uploads/')->add('../my-file.txt', false); // '/path/to/my-file.txt'

Path::newDir('\\path\\to\\file.txt');               // '/path/to/file.txt' (on a *nix OS)
Path::newDir('/path/to/file.txt');                  // '/path/to/file.txt' (on a *nix OS)
Path::newDir('/path/to/file.txt')->separator('\\'); // '\path\to\file.txt'

$pathA = Path::new('/path/to/file.txt');
$pathB = $pathA->copy();
$pathB !== $pathA; // true

$pathA = PathImmutable::newDir('/path/to/');
$pathB = $pathA->add('file.txt');
$pathA !== $pathB; // true