How can PHP code be optimized to efficiently detect and store the user's operating system for future use?

To efficiently detect and store the user's operating system in PHP, you can use the $_SERVER['HTTP_USER_AGENT'] variable to retrieve the user's user agent string, which contains information about their operating system. You can then parse this string to extract the operating system information and store it in a session variable for future use.

$user_agent = $_SERVER['HTTP_USER_AGENT'];

$os = "Unknown";

if (strpos($user_agent, 'Windows') !== false) {
    $os = 'Windows';
} elseif (strpos($user_agent, 'Macintosh') !== false) {
    $os = 'Macintosh';
} elseif (strpos($user_agent, 'Linux') !== false) {
    $os = 'Linux';
}

$_SESSION['user_os'] = $os;