检查PHP中的相对vs绝对路径/ URL

Yar*_*rin 8 php url relative-path absolute-path relative-url

我需要实现函数来检查路径和URL是相对的,绝对的还是无效的(语法上无效 - 不管资源是否存在).我应该寻找的案件范围是什么?

function check_path($dirOrFile) {
    // If it's an absolute path: (Anything that starts with a '/'?)
        return 'absolute';
    // If it's a relative path: 
        return 'relative';
    // If it's an invalid path:
        return 'invalid';
}

function check_url($url) {
    // If it's an absolute url: (Anything that starts with a 'http://' or 'https://'?)
        return 'absolute';
    // If it's a relative url:
        return 'relative';
    // If it's an invalid url:
        return 'invalid';
}
Run Code Online (Sandbox Code Playgroud)

Dev*_*per 9

使用:

\n
function isAbsolute($url) {\n  return isset(parse_url($url)['host']);\n}\n
Run Code Online (Sandbox Code Playgroud)\n

解释:

\n

如果设置了主机,则路径是绝对路径。

\n

例如:

\n
$test = [\n'/link?param=1'=>parse_url('/assa?ass'),\n'//aaa.com/link?param=1'=>parse_url('//assa?ass'),\n'http://aaa.com/link?param=1'=>parse_url('http://as.plassa?ass')\n];\nvar_export($test);\n\n/* Output:\n[\n  "/link?param=1" => array:2 [\xe2\x96\xbc // Not absolute\n    "path" => "/assa"\n    "query" => "ass"\n  ]\n  "//aaa.com/link?param=1" => array:2 [\xe2\x96\xbc // Absolute because of host\n    "host" => "assa"\n    "query" => "ass"\n  ]\n  "http://aaa.com/link?param=1" => array:3 [\xe2\x96\xbc // Absolute because of host\n    "scheme" => "http"\n    "host" => "as.plassa"\n    "query" => "ass"\n  ]\n]\n*/\n
Run Code Online (Sandbox Code Playgroud)\n


小智 5

绝对路径和URL

您是正确的,Linux中的绝对URL必须以开头/,因此检查路径开头的斜杠就足够了。

对于网址,你需要检查http://https://,因为你写的,但是,也有多个URL开始ftp://sftp://smb://。因此,这取决于您要涵盖的使用范围。

无效的路径和URL

假设您使用的是Linux,则路径中唯一禁止使用的字符为/\0。这实际上是非常依赖文件系统的,但是,您可以假定上述内容在大多数情况下都是正确的。

在Windows中,它更为复杂。您可以在Path.GetInvalidPathChars方法文档中的“备注”下阅读有关它的信息

网址是比Linux多的路径复杂,作为唯一允许的字符是A-Za-z0-9-._~:/?#[]@!$&'()*+,;=(在另一个答案描述在这里)。

相对路径和URL

通常,既不是绝对也不是无效的路径和URL是相对的。

  • 如果您希望PHP脚本可移植到其他平台,那么仅检查斜杠是不够的-Windows上的绝对路径可能以反斜杠或“ C:\”开头...我想出了以下内容( Preg)正则表达式:`/ ^(?:\ / | \\ | \ w \:\\)。* $ /`-匹配`“ / file”`,`“ \ file”`,`“ c :\ file“`,而不是`” file“`或`” path / file“`等。 (6认同)