Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

RoffDaniel's avatar

How to run php script before user connection?

Good evening everyone. The question arose of the implementation of the iso definition of the user's country code, to determine his language. This question is currently implemented as follows:

JS

$(document).ready(function () {
    $.ajax({
        type: "POST",
        url: "{{ route('check_locale') }}",
        contentType: false,
        processData: false,
        async: true,
        dataType: "json",
        data: {_token: $('meta[name="csrf-token"]').attr('content')},
        timeout: 3000
    });
    return false;
});

PHP

public function check_user_locale() {
    $reader = new Reader(resource_path('assets/geoip/GeoLite2-City.mmdb'));
    if ($this->check_ip->getUserIpAddr() == '127.0.0.1') {
        $ip = '8.8.8.8';
    } else { $ip = $this->check_ip->getUserIpAddr(); }
    $record = $reader->city($ip);
    // Change locale
    $locale = session()->get('locale');
    $country_code = $record->country->isoCode;
    if (!isset($locale)) {
        switch ($country_code) {
            case "UA":
                session()->put('locale', 'ua');
                App::setLocale('ua');
                break;
            case 'RU':
            case 'BY':
                session()->put('locale', 'ru');
                App::setLocale('ru');
                break;
            default:
                session()->put('locale', 'en');
                App::setLocale('en');
                break;
        }
    } else {
        return false;
    }
}

But this option is not correct, since it works only when the user actually connected to the site and received the content

Please tell me how can I run this function before connecting or during? Thanks in advance!

0 likes
1 reply
tykus's avatar
tykus
Best Answer
Level 104

Use a middleware to intercept the Request; check for an existing locale stored in the Session; or, execute your logic above and redirect to the intended URL after putting to the Session.

You can add this middleware to the protected $middleware array in App\Http\Kernel class so that it is run on every Request.

1 like

Please or to participate in this conversation.