| 1 |
<?php |
| 2 |
|
| 3 |
namespace FileUtil; |
| 4 |
|
| 5 |
use FileUtil\FileExists; |
| 6 |
|
| 7 |
/** |
| 8 |
* |
| 9 |
* |
| 10 |
* @package FileUtil |
| 11 |
* @author Bjørn Rosell <[email protected]> |
| 12 |
*/ |
| 13 |
class PathValidator |
| 14 |
{ |
| 15 |
/** |
| 16 |
* Check if path looks valid and doesn't contain suspecious patterns. |
| 17 |
|
| 18 |
* The path must meet the following criteria: |
| 19 |
* |
| 20 |
* - It must be a string |
| 21 |
* - No NUL character |
| 22 |
* - No control characters between 0-20 |
| 23 |
* - No phar stream wrapper |
| 24 |
* - No php stream wrapper |
| 25 |
* - No glob stream wrapper |
| 26 |
* - Not empty path |
| 27 |
* |
| 28 |
* @throws \Exception In case the path doesn't meet all criteria |
| 29 |
*/ |
| 30 |
public static function checkPath($path) |
| 31 |
{ |
| 32 |
if (gettype($path) !== 'string') { |
| 33 |
throw new \Exception('File path must be string'); |
| 34 |
} |
| 35 |
if (strpos($path, chr(0)) !== false) { |
| 36 |
throw new \Exception('NUL character is not allowed in file path!'); |
| 37 |
} |
| 38 |
if (preg_match('#[\x{0}-\x{1f}]#', $path)) { |
| 39 |
// prevents line feed, new line, tab, charater return, tab, ets. |
| 40 |
throw new \Exception('Control characters #0-#20 not allowed in file path!'); |
| 41 |
} |
| 42 |
// Prevent phar stream wrappers (security threat) |
| 43 |
if (preg_match('#^phar://#', $path)) { |
| 44 |
throw new \Exception('phar stream wrappers are not allowed in file path'); |
| 45 |
} |
| 46 |
if (preg_match('#^(php|glob)://#', $path)) { |
| 47 |
throw new \Exception('php and glob stream wrappers are not allowed in file path'); |
| 48 |
} |
| 49 |
if (empty($path)) { |
| 50 |
throw new \Exception('File path is empty!'); |
| 51 |
} |
| 52 |
} |
| 53 |
|
| 54 |
/** |
| 55 |
* Check if path points to a regular file (and doesnt match suspecious patterns). |
| 56 |
* |
| 57 |
* @throws \Exception In case the path doesn't point to a regular file or matches suspecious patterns |
| 58 |
*/ |
| 59 |
public static function checkFilePathIsRegularFile($path) |
| 60 |
{ |
| 61 |
self::checkPath($path); |
| 62 |
|
| 63 |
if (!FileExists::fileExists($path)) { |
| 64 |
throw new \Exception('File does not exist'); |
| 65 |
} |
| 66 |
if (@is_dir($path)) { |
| 67 |
throw new \Exception('Expected a regular file, not a dir'); |
| 68 |
} |
| 69 |
} |
| 70 |
} |
| 71 |
|