Note that there are many types of possible file paths. For example:
- "./"
- "../"
- "........" (yes, it could be a file name)
- "File / file.txt"
- File / File
- "file.txt"
- "File /../.// file / file / file"
- "/file/.././/file/file/.file" (UNIX)
- "C: \ Windows \" (Windows)
- "C: \ Windows \ asd / asd" (Windows php accepts this)
- "File /../.// file / file / file! @ # $"
- "File /../.// file / file / file! @ #. Php.php.php.pdf.php"
All of these file paths are valid. I can't think of a simple regex that can make it perfect.
Suppose this is just a UNIX path, this is what I think should work in most cases:
preg_match('/^[^*?"<>|:]*$/',$path)
It checks the entire string for ^, *,?, ", <,>, | ,:: (removes this for windows). These are all characters that do not allow you to specify the file name with / and.
If these are windows, you should replace the path \ with /, and then explode it and check if it is absolute. Here is one example that works on both unix and windows.
function is_filepath($path) { $path = trim($path); if(preg_match('/^[^*?"<>|:]*$/',$path)) return true; // good to go if(!defined('WINDOWS_SERVER')) { $tmp = dirname(__FILE__); if (strpos($tmp, '/', 0)!==false) define('WINDOWS_SERVER', false); else define('WINDOWS_SERVER', true); } /*first, we need to check if the system is windows*/ if(WINDOWS_SERVER) { if(strpos($path, ":") == 1 && preg_match('/[a-zA-Z]/', $path[0])) // check if it something like C:\ { $tmp = substr($path,2); $bool = preg_match('/^[^*?"<>|:]*$/',$tmp); return ($bool == 1); // so that it will return only true and false } return false; } //else // else is not needed return false; // that t }
Mo lam
source share