skip to Main Content

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.

2

Answers


  1. 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
    }
    
    Login or Signup to reply.
  2. You can also use Spatie/Url to check both hosts and compare to each other

    <?php
    
    use SpatieUrlUrl;
    
    $requestHost = Url::fromString(request()->url())->getHost();
    $appHost = Url::fromString(config('app.url'))->getHost();
    
    if ($requestHost === $appHost) {
        return redirect();
    } 
    
    return redirect(); 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search