Detect screen resolution using PHP
The ability to detect your website visitor's screen resolution gives you more freedom on how you want to display your website's content to the end user. This will help you to remove unnecessary scrollbars, that appear when the user's screen resolution is low, by serving the right version of the webpage. By default there is no such function in PHP which detects display resolution. Still there is an easy work around and it is achieved by using JavaScript along with PHP. Javascript provides the user's screen resolution information and this can be accessed by using the screen.width and screen.height properties.
Check out the Javascript code given below:
<script language='JavaScript'>
<!--
function detect()
{
alert('Screen resolution is '+screen.width+'x'+screen.height+'.');
}
//-->
</script>
<a href='#' onclick='detect();return false;'>Detect Screen Resolution</a>
Here in detect() function we are using screen.width and screen.height to get the user's screen resolution. Check out the demo below.
Now we will use this same JavaScript code to detect user's screen resolution and then pass this information to PHP so that the final page can be generated according to the user's display resolution.
Create a new PHP file, say index.php and add following code to it:
<?php
if(!isset($_GET['screen_check']))
{
/* This code will be executed if screen resolution has not been detected.*/
echo "<script language='JavaScript'>
<!--
document.location=\"$PHP_SELF?screen_check=done&Width=\"+screen.width+\"&Height=\"+screen.height;
//-->
</script>";
}
else
{
/* This code will be executed after screen resolution is detected.*/
if(isset($_GET['Width']) && isset($_GET['Height'])) {
// Resolution detected
echo "<h1>Your screen resolution is ".$_GET['Width']." x ".$_GET['Height'].".</h1><br />";
//Display page as per resolution
if(($_GET['Width']>1024)&&($_GET['Height']>768)) {
echo "<b>This will be displayed when screen resolution is greater than 1024x768.</b>";
}
else {
//Display page as per resolution
echo "<b>This will be displayed when screen resolution is either equal to or less than 1024x768.</b>";
}
}
else {
// Resolution not detected
}
}
?>
Here we first check whether the PHP variable screen_check has been set or not. If it is not so then we use JavaScript to detect the user's screen resolution and post back the result via GET method. This information can then used be to render the web-page according to the screen resolution of the user. You can use different CSS stylesheets for different screen resolutions and load them accordingly. You can also store this information in a cookie and every time user goes to a new page you can retrieve the cookie's value and display pages according to it. A screenshot of the above code is shown below.