检查 PHP 中的相对路径和绝对路径/URL [英] Checking for relative vs absolute paths/URLs in PHP

查看:90
本文介绍了检查 PHP 中的相对路径和绝对路径/URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要实现函数来检查路径和 url 是相对的、绝对的还是无效的(语法上无效 - 不是资源是否存在).我应该寻找哪些案例?

I need to implement functions to check whether paths and urls are relative, absolute, or invalid (invalid syntactically- not whether resource exists). What are the range of cases I should be looking for?

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';
}

推荐答案

绝对路径和 URL

您说得对,Linux 中的绝对 URL 必须以 / 开头,因此检查路径开头是否有斜杠就足够了.

You are correct, absolute URLs in Linux must start with /, so checking for a slash in the start of the path will be enough.

对于 URL,您需要检查 http://https://,如您所写,但是,还有更多以 ftp 开头的 URL://sftp://smb://.所以这很大程度上取决于你想要覆盖的用途范围.

For URLs you need to check for http:// and https://, as you wrote, however, there are more URLs starting with ftp://, sftp:// or smb://. So it is very depending on what range of uses you want to cover.

无效的路径和网址

假设您指的是 Linux,路径中唯一禁止使用的字符是 /\0.这实际上非常依赖于文件系统,但是,您可以假设上述内容对于大多数用途都是正确的.

Assuming you are referring to Linux, the only chars that are forbidden in a path are / and \0. This is actually very filesystem dependent, however, you can assume the above to be correct for most uses.

在 Windows 中它更复杂.您可以在 Path.GetInvalidPathChars 方法 备注下的文档.

In Windows it is more complicated. You can read about it in the Path.GetInvalidPathChars Method documentation under Remarks.

URL 比 Linux 路径更复杂,因为唯一的允许字符是 AZaz0-9-._~:/, ?, #, [, ], @, !, $, &, ', (, )*+;=(如另一个答案此处中所述).

URLs are more complicated than Linux paths as the only allowed chars are A-Z, a-z, 0-9, -, ., _, ~, :, /, ?, #, [, ], @, !, $, &, ', (, ), *, +, ,, ; and = (as described in another answer here).

相对路径和网址

一般来说,既不是绝对也不是无效的路径和 URL 是相对的.

In general, paths and URLs which are neither absolute nor invalid are relative.

这篇关于检查 PHP 中的相对路径和绝对路径/URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆