Detect the display resolution

user3463111 picture user3463111 · Oct 1, 2014 · Viewed 12.9k times · Source

I need the help from people detecting the display resolution of a device using PHP.

My code is in trouble when switching interface I have the following code:

 $_page="home";
 if(get('page'))
    $_page=strtolower(get('page'));
 // Check if larger than 800px screen will show this code.
 $_pagePath='Includes/desktop/'.$_page.'_left.php';
 // Check if the screen is smaller than 800px will display this code.
 $_pagePath='Includes/mobile/'.$_page.'_left.php';  
 if(file_exists($_pagePath))
            include $_pagePath;
 else
    echo 'File '.$_pagePath.' not found';

Please help me finish this code.

Answer

dingensundso picture dingensundso · Oct 1, 2014

You won't be able to detect the screen size with PHP, because PHP is serverbased. You could however detect the screensize with javascript and tell the server. Easiest way to accomplish this, would be to set a cookie.

Since you didn't say whether you want width or height, I assume in the following code that you are just interested in the bigger one of those.

<script type="text/javascript">
  var c=document.cookie;
  document.cookie='size='+Math.max(screen.width,screen.height)+';';
</script>

And then check it in your PHP script with

if($_COOKIE["size"]>800)
  $_pagePath='Includes/mobile/'.$_page.'_left.php'; 
else
  $_pagePath='Includes/desktop/'.$_page.'_left.php'; 

The only problem with this approach is that if a user connects for the first time he doesn't have the cookie yet, so the server won't know the resolution. Same applies for user who don't accept cookies.