Search code examples
phplaravelurlhttp-redirecthost

Laravel is there a way to detect if a given url have the same host as my project host?


Basically I'm writing a snippet that checks whether or not a given link have the same host as my server host. For example a given link is https://example.test/another_link and my host is not_example.test. So basically if it is the same then I'll redirect to that normally but if not then I'd have to redirect to my home page (https://not_example.test/home).

I tried hardcoding it but issue is some of my co-workers have different host names like not_example1.test so basically I hate to ask them to change it every time. Obviously Route::has only works if it have a named route and if our route list expands it's gonna be a pain to add every named route.


Solution

  • You can use request()->getHttpHost() to compare it with a given URL from input, and you can get the host of a given URL by a multiple ways, the easiest way is to get is using parse_url

    $inputUrl = parse_url(request()->get('some_input'),  PHP_URL_HOST);
    if (request()->getHttpHost() == $inputUrl) {
       // do something
    }