title: Get user's screen&viewport dimensions in php on first load
body: <p>I want to get in PHP the height/width of both the screen and the viewport when a user visits a page.</p>
  
  <p>I've tried different ways but they all cause other problems.</p>
  
  <p>My goals:</p>
  
  <ul>
  <li><p>Get the info on the first load (no jump page, no reload).</p></li>
  <li><p>Not change the url</p></li>
  <li><p>Not affect the rest of the PHP that runs on load, or make that PHP
  run twice</p></li>
  </ul>
  
  <p>What I've tried so far:</p>
  
  <p>Javascript to get viewport dimensions:</p>
  
  <pre><code>if(!isset($_POST['width']) || !isset($_POST['height'])) {
  echo '
  &lt;script type="text/javascript" src="jquery.min.js"&gt;&lt;/script&gt;
  &lt;script type="text/javascript"&gt;
  $(document).ready(function () {
      var height = $(window).height();
      var width = $(window).width();
      $.ajax({
          type: \'POST\',
          data: {
              "height": height,
              "width": width
          },
          success: function (data) {
              $("body").html(data);
          },
      });
  });
  &lt;/script&gt;
  ';
  }
  
  $user_width = $_POST['width'];
  $user_height = $_POST['height'];
  </code></pre>
  
  <p>problems: causes all php to run twice, once on load, once when it returns a value (the second time is about 4 seconds after the first), which makes the rest of the php wacky... also, makes page load very slow</p>
  
  <p>Putting the screen dimensions into the url:</p>
  
  <pre><code>if(isset($_SESSION['screen_width']) AND isset($_SESSION['screen_height'])){
      $user_width = $_SESSION['screen_width'];
      $user_height = $_SESSION['screen_height'];
      } else if(isset($_REQUEST['width']) AND isset($_REQUEST['height'])) {
          $_SESSION['screen_width'] = $_REQUEST['width'];
          $_SESSION['screen_height'] = $_REQUEST['height'];
          header('Location: ' . $_SERVER['PHP_SELF']);
      } else {
          echo '&lt;script type="text/javascript"&gt;window.location = "' . $_SERVER['PHP_SELF'] . '?width="+screen.width+"&amp;height="+screen.height;&lt;/script&gt;';
      }
  </code></pre>
  
  <p>problems: changes the url (which affects other code and looks bad compared to expressionless urls which they have now); doesn't return viewport size afaik</p>
  
  <p>I'm a noob. Maybe it's easy to do, but I really don't know. I searched a lot. That's how I got methods above. But I couldn't get them to work for me. Afaik, I haven't seen a solution anywhere to a similar situation.</p>
  
  <p>Thanks :)</p>