When you coding for dynamic website, you may need to know screen resolution of the client's machine. How can you get it?

For client side, there is very simple way to get it by using javascript as javascript running in client's machine. But you cannot detect the client's resolution directly in server side as server side script running in server. So, you may ask, what you have to do if you need to know client's screen resolution in server side? That's easy. What you need to do is just communicate between client and server.

Detecting the client's screen resolution

use screen.width to get screen width use screen.height to get screen height
	function ShowScreenResolution(){

		var w = screen.width;
		var h = screen.height;

		alert( "Your screen resolution is " + w + 'x' + h);


Server Side

In server side script, I check the session in page load whether width and height data exist or not. If not exist, I injected the JavaScript code to sent back the screen size when visitor load the page first time. Then I maintain the data in session. Following is JavaScript code to inject when page load. Put it within body tags of your page if width and height data does not exist in session value. Don't forget to omit the JavaScript code after you put data into session. Otherwise, your page will be refresh again and again.
<script type="text/javascript">
 location.replace('http://www.yourdomain.com/index.php?w=' + screen.width + '&h='  + screen.height );
Put data into session.
 $_SESSION['width'] = $_GET['w']; // store session data
 $_SESSION['height'] = $_GET['h']; // store session data
Check session whether you need to inject the JavaScript code or not.
if ($_SESSION['width']!=null){
//echo javascript-code;
The best way to post back data is using Ajax. So user may not notice when the page refresh in first visit.

author's photo

Author : Blue Cloud

Just a normal software developer who love to write code. Developing professional software since 1999. After working in the software industry for many years, I've started my own website to share knowledges and experiences.

blog comments powered by Disqus