How can user agents be utilized in PHP to determine the type of device accessing a website?

User agents can be utilized in PHP to determine the type of device accessing a website by accessing the $_SERVER['HTTP_USER_AGENT'] variable. This variable contains information about the user's browser, operating system, and device. By parsing this information, we can identify the type of device and customize the website's content or layout accordingly.

$user_agent = $_SERVER['HTTP_USER_AGENT'];

if (strpos($user_agent, 'iPhone') !== false) {
    echo 'This is an iPhone';
} elseif (strpos($user_agent, 'Android') !== false) {
    echo 'This is an Android device';
} elseif (strpos($user_agent, 'Windows Phone') !== false) {
    echo 'This is a Windows Phone';
} else {
    echo 'Unknown device';
}