mpen
mpen

Reputation: 283313

Determine if path is remote or local

I have an array that looks like this:

Array
(
    [0] => public\js\jade\runtime.js
    [1] => public\js\templates.js
    [2] => public\js\underscore.js
    [3] => public\js\underscore.string.js
    [4] => public\js\main.js
    [5] => //ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js
)

I need to determine which of those files is local or remote. i.e., only [5] is remote. Is there a method for doing this?

Upvotes: 5

Views: 2894

Answers (5)

DimMav
DimMav

Reputation: 31

You can use realpath(). This function returns false on failure, e.g. if the file does not exist or is remote:

<?php
$paths = array(
    'public\js\jade\runtime.js',
    'public\js\templates.js',
    'public\js\underscore.js',
    'public\js\underscore.string.js',
    'public\js\main.js',
    '//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'
);
foreach ($paths as $path)
    if (realpath($path))
        echo("'$path' is local and exists." . PHP_EOL);
    else
        echo("'$path' is remote or doesn't exist." . PHP_EOL);
?>

Upvotes: 2

Madsem
Madsem

Reputation: 11

This is old, I know.

I think the best way to check if a path is local or not is to simply check if it exists :)

For example:

if (file_exists($path)) {
        unlink($path);
    } else {
        // delete remote file

    }

Upvotes: 0

mpen
mpen

Reputation: 283313

Gave this some thought. Here's my solution:

function isLocal($path) {
    return preg_match('~^(\w+:)?//~', $path) === 0;
}

Although it will fail for file:///path/to/my/file (should return true), but I'm not sure I care about that case right now.

Upvotes: 0

Connor Peet
Connor Peet

Reputation: 6265

The simplest way would be a search for a double slash. Although it would be valid to have in a relative path, it would come after a period (any domain or IP), a GET variable (.js?variables//), or another path (js/path//to.js). The following code accounts for these.

foreach ($array as $path) {
    if (strpos($path, '//') >= max(strpos($path, '.'), strpos($path, '/'))) {
        #absolute!
    } else {
        #relative!
    }
}

Upvotes: 2

dev-null-dweller
dev-null-dweller

Reputation: 29482

You can do it with parse_url. Example:

function is_path_remote($path) {
    $my_host_names = array(
       'my-hostname.com',
       'www.my-hostname.com'
    );
    $host = parse_url($path, PHP_URL_HOST);
    if ($host === NULL || in_array($host, $my_host_names)) {
        return false;
    } else {
        return true;
    }
}

Upvotes: 6

Related Questions