mpen mpen - 1 year ago 94
PHP Question

How to determine if a file path is absolute?

How can I determine if a file path is absolute? Must work on both Windows and Linux.

Answer Source

Here my try at doing it with a single function:

function isAbsolutePath($path) {
    if (!is_string($path)) {
        $mess = sprintf('String expected but was given %s', gettype($path));
        throw new \InvalidArgumentException($mess);
    if (!ctype_print($path)) {
       $mess = 'Path can NOT have non-printable characters or be empty';
       throw new \DomainException($mess);
    // Optional wrapper(s).
    $regExp = '%^(?<wrappers>(?:[[:print:]]{2,}://)*)';
    // Optional root prefix.
    $regExp .= '(?<root>(?:[[:alpha:]]:/|/)?)';
    // Actual path.
    $regExp .= '(?<path>(?:[[:print:]]*))$%';
    $parts = [];
    if (!preg_match($regExp, $path, $parts)) {
        $mess = sprintf('Path is NOT valid, was given %s', $path);
        throw new \DomainException($mess);
    if ('' !== $parts['root']) {
        return true;
    return false;

I took this from one of my project you might find useful while working with files and paths: dragonrun1/file_path_normalizer

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download