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';
}
Absolute Paths and URLs
You are correct, absolute URLs in Linux must start with /
, so checking for a slash in the start of the path will be enough.
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.
Invalid Paths and URLs
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.
In Windows it is more complicated. You can read about it in the Path.GetInvalidPathChars Method documentation under Remarks.
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).
Relative Paths and URLs
In general, paths and URLs which are neither absolute nor invalid are relative.