Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking for relative vs absolute paths/URLs in PHP

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';
}
like image 961
Yarin Avatar asked Sep 12 '11 18:09

Yarin


People also ask

How do you know if a URL is relative or absolute?

Original Answer. This will recognize an absolute URL, if: URL contains "://" anywhere after the first character, or. URL starts with "//" (protocol relative)

Should I use absolute or relative URLs?

If you do a lot of testing and move content frequently between domains, then relative links are the best solution. Absolute paths are more secure, protect content, and prevent duplicate pages. The main point is that the link format you prefer should be applied to all URLs on the site.

What is absolute URLs and relative URLs explain using examples?

For example, https://cart.com is an absolute URL. Relative URLs. A relative URL typically contains only the path to a specific file. In context to the Cart.com online stores system, these typically begin with a forward slash. The forward slash tells the browser to go to the domain of the site and look for a file.

How do you tell if a path is an absolute path?

A path is either relative or absolute. An absolute path always contains the root element and the complete directory list required to locate the file. For example, /home/sally/statusReport is an absolute path. All of the information needed to locate the file is contained in the path string.


1 Answers

From Symfony FileSystem component to check if a path is absolute:

public function isAbsolutePath($file)
{
    return strspn($file, '/\\', 0, 1)
        || (strlen($file) > 3 && ctype_alpha($file[0])
            && substr($file, 1, 1) === ':'
            && strspn($file, '/\\', 2, 1)
        )
        || null !== parse_url($file, PHP_URL_SCHEME)
    ;
}
like image 85
CIRCLE Avatar answered Oct 26 '22 01:10

CIRCLE