phpurlurirfc3986percent-encoding

PHP: comparing URIs which differ in percent-encoding


In PHP, I want to compare two relative URLs for equality. The catch: URLs may differ in percent-encoding, e.g.

According to RFC 3986, servers should treat these URIs identically. But if I use == to compare, I'll end up with a mismatch.

So I'm looking for a PHP function which will accepts two strings and returns TRUE if they represent the same URI (dicounting encoded/decoded variants of the same char, upper-case/lower-case hex digits in encoded chars, and + vs. %20 for spaces), and FALSE if they're different.

I know in advance that only ASCII chars are in these strings-- no unicode.


Solution

  • function uriMatches($uri1, $uri2)
    {
        return urldecode($uri1) == urldecode($uri2);
    }
    
    echo uriMatches('/dir/file+file', '/dir/file%20file');      // TRUE
    echo uriMatches('/dir/file(file)', '/dir/file%28file%29');  // TRUE
    echo uriMatches('/dir/file%5bfile', '/dir/file%5Bfile');    // TRUE
    

    urldecode