Search code examples
phpjavascriptajaxresolution

Client display resolution detection


Currently I'm using following PHP+JavaScript code to detect clients browser windows size

$url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
if(isSet($_GET['w']) && isSet($_GET['h']))
{
$w = $_GET['w']; 
$h = $_GET['h'];
}


if(!$w && !$h)
{
    $pos= strpos($url, '?');
    if($pos===false)
    {
echo '<script type="text/javascript">';
echo "var w = screen.width;
var h = screen.height;
window.location.href = '".$url."?w='+w+'&h='+h;
</script>'";
}

else {
echo '<script type="text/javascript">';
echo "var w = screen.width;
var h = screen.height;
window.location.href =  '".$url."&w='+w+'&h='+h;
</script>'";
}
}

I wonder, is there any way to optimize code (post via ajax, .. etc) or easy way to do it?


Solution

  • not really as you have to do a round trip to the broser first to determine the screensize.

    If you need the screensize for subsequent request only, you could do an ajax call and save the values in the session (jquery example):

    $(document).ready(function() {
      var w = screen.width;
      var h = screen.height;
      $.load('/yourPhpScriptToSaveTheSession.php?&w='+w+'&h='+h);
    });