What is the UserAgent class in CodeIgniter 4?
Why Interviewers Ask This
This tests whether you can apply CodeIgniter knowledge to real-world scenarios. Interviewers are looking for clarity of thought and evidence that you've encountered this in production code.
Answer
The UserAgent class in CI4 parses the browser's User-Agent string to identify the browser, platform, mobile device, and robot. Get it: $agent = service("request")->getUserAgent(). Detect browser: $agent->isBrowser() (is it a browser?), $agent->getBrowser() (returns browser name like "Chrome"), $agent->getVersion(). Platform: $agent->isPlatform("Windows"), $agent->getPlatform(). Mobile: $agent->isMobile(), $agent->getMobile(). Robot/Bot: $agent->isRobot(), $agent->getRobot(). Referral: $agent->isReferral(), $agent->getReferrer(). Use cases: serving mobile-optimized content, blocking bots from certain pages, logging user device statistics, and adjusting UI based on browser capabilities. Note that User-Agent strings can be spoofed — do not rely on them for security decisions.
Common Mistake
A common mistake is memorizing definitions without understanding implications. When asked this question, go one level deeper — explain what happens when this concept is misused or ignored.