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)
使用:
\nfunction isAbsolute($url) {\n return isset(parse_url($url)['host']);\n}\nRun 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*/\nRun Code Online (Sandbox Code Playgroud)\n
小智 5
绝对路径和URL
您是正确的,Linux中的绝对URL必须以开头/,因此检查路径开头的斜杠就足够了。
对于网址,你需要检查http://和https://,因为你写的,但是,也有多个URL开始ftp://,sftp://或smb://。因此,这取决于您要涵盖的使用范围。
无效的路径和URL
假设您使用的是Linux,则路径中唯一禁止使用的字符为/和\0。这实际上是非常依赖文件系统的,但是,您可以假定上述内容在大多数情况下都是正确的。
在Windows中,它更为复杂。您可以在Path.GetInvalidPathChars方法文档中的“备注”下阅读有关它的信息。
网址是比Linux多的路径复杂,作为唯一允许的字符是A-Z,a-z,0-9,-,.,_,~,:,/,?,#,[,],@,!,$,&,',(,),*,+,,,;和=(在另一个答案描述在这里)。
相对路径和URL
通常,既不是绝对也不是无效的路径和URL是相对的。
| 归档时间: |
|
| 查看次数: |
12264 次 |
| 最近记录: |