Tuesday, February 12, 2013

Screen Resolution in PHP

Screen Resolution in PHP

I was trying to get Screen resolution using PHP server side program, only to find out that it is not possible! Logically speaking too, PHP will be parsed on the server, prior showing it to the User. So the screen resolution will be on the client side e.g. the browser.

However using simple Javascript and cookie we can send the Screen size to the Server. The logic flow is
1. Get the screen resolution using Javascript
2. Store the screen size data into a cookie using Javascript
3. Read the data from the cookie using PHP
4. Use this data as you want.

A simple PHP Script to get the Screen resolution would be
<?php

if(!isset($_COOKIE['screen_resolution'])) {
//No cookie found so get the screen resolution using Javascript and store it in cookie
echo '<script type="text/javascript">width = screen.width; height=screen.height; document.cookie="screen_resolution="+width+"X"+height;</script>';
echo "Since this was the first visit, we set your Screen Resolution cookie just now.<br/> Refresh this page to see your screen resolution";}

else {
//Since Cookie is found so get the screen resolution from  this cookie
$screen_size=$_COOKIE['screen_resolution'];
echo "We got the details from Screen Resolution cookie.<br/><br/><b>Your Screen size is";
$screen_size=explode ('X', $screen_size);
$screen_width=$screen_size[0];
$screen_height=$screen_size[1];
$content .="<br/>Width : $screen_width<br/>Height : $screen_height</b>";}

?>
You can use $screen_width or $screen_height later as session variable and use it anywhere you want in your PHP script.

Beware though that this method will not tell you about Window size, so if your Website visitors customize the browser size this script will not detect that, and will still tell you only the screen size.

For more posts like these visit www.internet-programs.com/forum/