0

If I have two URLs in PHP (e.g. /r/jquery.js and http://domain.tld/r/jquery.js), is there a clean way to compare those two, interpreted in a way the browser would interpret them when visiting a specified URL?

So for this comparison, three URLs are given:

  • $url_a - the URL to compare with $url_b
  • $url_b - the URL to compare with $url_a
  • $url_c - the base for relative URLs

For example:
If $url_a = '/r/jquery.js' and $url_b = 'http://domain.tld/r/jquery.js', the comparison

  • should give true if $url_c = 'http://domain.tld/s/index.php'
  • should give false if $url_c = 'https://domain.tld/s/index.php'
  • should give false if $url_c = 'http://subdomain.domain.tld/s/index.php'

I am searching for a full solution including facets like /r///../r/jquery.js can equal http://domain.tld/r/jquery.js (depending on $url_c) and much more.

Since there are probably more facets than a layman (as me) knows, I think a library or built-in PHP-feature would be required. While I would also be interested in Linux command line tools, that would not be the best bet, because my testing environment is windows, although I deploy to Linux.

Off-Topic / Background information:

I am currently implementing a system into my website that manages JavaScript, CSS and other dependencies. For this sake I need to compare, whether a JavaScript file is already implemented/a dependency or not. But at that point I have only URLs to those files (Which is perfectly fine! I will not change that!).

Matteo B.
  • 3,906
  • 2
  • 29
  • 43

1 Answers1

1

The way to go is (as suggested by @scunliffe and @James):

Convert both to absolute URLs and then compare the strings equality.

https://github.com/monkeysuffrage/phpuri

EDIT:

Yet untested:

require_once 'phpuri.php';
function urlsEqual($urlA, $urlB, $base) {
    $oBase = phpUri::parse($base);
    $oUrlA = $oBase->join($urlA);
    $oUrlB = $oBase->join($urlB);
    return $oUrlA == $oUrlB;
}

$url_a = '/r/jquery.js';
$url_b = 'http://domain.tld/r/jquery.js';
$url_c = 'http://domain.tld/s/index.php';
if(urlsEqual($url_a, $url_b, $url_c))
    echo $url_a.' == '.$url_b;
else
    echo $url_a.' != '.$url_b;
Matteo B.
  • 3,906
  • 2
  • 29
  • 43