Search code examples
phpregexyii

Check if two URL strings are the same PHP


How to check if two URL strings are the same for example

http://example.com

http://example.com/

https://example.com/

http://example.com/#

All the above url points to same page

Suppose i am having a directory of urls in my database and i am adding a url to the database which is already present. how can i validate for uniqueness for the above scenario using PHP.


Solution

  • Use parse_url to break down the URLs into parts and compare those that must match for your definition of "the same".

    For example:

    function areUrlsTheSame($url1, $url2)
    {
        $mustMatch = array_flip(['host', 'port', 'path']);
        $defaults = ['path' => '/']; // if not present, assume these (consistency)
        $url1 = array_intersect_key(parse_url($url1), $mustMatch);
        $url2 = array_intersect_key(parse_url($url2), $mustMatch);
    
        return $url1 === $url2;
    }
    

    See it in action.