请注意,有许多可能的文件路径类型。
例如:
- "./"
- "../"
- "........"(是的,这可以是文件名)
- "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 接受此格式)
- "file/.././/file/file/file!@#$"
- "file/.././/file/file/file!@#.php.php.php.pdf.php"
所有这些文件路径都是有效的。我想不出一个简单的正则表达式可以完美解决。
现在假设它只是 UNIX 路径,这是我认为应该适用于大多数情况的内容:
preg_match('/^[^*?"<>|:]*$/',$path)
它检查所有字符串中的 ^, *, ?, ", <, >, | 和 :(在 Windows 中需要删除)。这些字符都是Windows不允许用于文件名的字符,以及 / 和 .
如果是Windows系统,您应该将路径中的 \ 替换为 /,然后分割它并检查是否为绝对路径。以下是一个同时适用于Unix和Windows的示例。
function is_filepath($path)
{
$path = trim($path);
if(preg_match('/^[^*?"<>|:]*$/',$path)) return true;
if(!defined('WINDOWS_SERVER'))
{
$tmp = dirname(__FILE__);
if (strpos($tmp, '/', 0)!==false) define('WINDOWS_SERVER', false);
else define('WINDOWS_SERVER', true);
}
if(WINDOWS_SERVER)
{
if(strpos($path, ":") == 1 && preg_match('/[a-zA-Z]/', $path[0]))
{
$tmp = substr($path,2);
$bool = preg_match('/^[^*?"<>|:]*$/',$tmp);
return ($bool == 1);
}
return false;
}
return false;
}