How to detect screen width with PHP
| Introduction | |
| PHP code example | |
| Result | |
| Code comments | |
| Check your HTTP_USER_AGENT |
Introduction
You often need to know the screen width in advance. In
CSS
the @media tag handles it.
For example, to hide a .rightBanner class block
on screens under 1000px, just write
@media screen and (max-width: 1000px) {
.rightBanner {display: none;}
}
And the browser, receiving such CSS from the server, hides the .rightBanner block on narrow screens.
You can detect the real current screen width with
JavaScript
there is an article about it
«Detecting screen width with JavaScript»
But what if you do not want to serve the browser some content at all. To save traffic or speed up page load.
The question arises - how to detect screen width at the server response stage.
Answer - you cannot. At least if you need the exact width and do not plan AJAX tricks.
If you just need to tell whether the visitor came from a mobile device or a desktop - shown below
PHP code example
<?php
function isMobile() {
return preg_match("/(android|avantgo|blackberry|bolt|boost|cricket|docomo|fone|hiptop|mini|mobi|palm|phone|pie|tablet|up\.browser|up\.link|webos|wos)/i", $_SERVER["HTTP_USER_AGENT"]);
}
$not_mobile = !(isMobile());
if ($not_mobile) {
echo'
<div class="rightBanner">
</div>
'
};
?>
Result
If the client browser passed one of the mentioned headers, the right block is not sent to it at all.
Code comments
preg_match returns 1 if it finds in
$_SERVER["HTTP_USER_AGENT"] one of the listed headers: android, avantgo, blackberry and so on.
In this case $not_mobile is 0 or FALSE and the if condition is not met.
The header list is probably already outdated as you read this, but first, you can extend it yourself. Second, whether you need every possible
header or just the main ones is up to you.
If you do not plan to reuse the function, one line is enough:
$not_mobile = !(preg_match("/(android|avantgo|blackberry|bolt|boost|cricket|docomo|fone|hiptop|mini|mobi|palm|phone|pie|tablet|up\.browser|up\.link|webos|wos)/i", $_SERVER["HTTP_USER_AGENT"]));
Your HTTP_USER_AGENT
In the next block you can see your HTTP_USER_AGENT
Today:
2026-10-26
Your HTTP_USER_AGENT:
Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; +claudebot@anthropic.com)
Check - whether the script recognized your device as mobile or not
Your device was not recognized as mobile
If the script misrecognized your device - message me on Telegram @andreyolegovichru
| PHP session locking | |
| Installing PHP frameworks | |
| Installing Yii | |
| Installing Symfony | |
| Installing Laravel | |
| Profiling PHP sites | |
| XDebug - debugging and profiling php code |
Article author: Andrei Olegovich