Get user's screen&viewport dimensions in php on first load
Asked Answered
L

2

8

I want to get in PHP the height/width of both the screen and the viewport when a user visits a page.

I've tried different ways but they all cause other problems.

My goals:

  • Get the info on the first load (no jump page, no reload).

  • Not change the url

  • Not affect the rest of the PHP that runs on load, or make that PHP run twice

What I've tried so far:

Javascript to get viewport dimensions:

if(!isset($_POST['width']) || !isset($_POST['height'])) {
echo '
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
$(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);
        },
    });
});
</script>
';
}

$user_width = $_POST['width'];
$user_height = $_POST['height'];

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

Putting the screen dimensions into the url:

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 '<script type="text/javascript">window.location = "' . $_SERVER['PHP_SELF'] . '?width="+screen.width+"&height="+screen.height;</script>';
    }

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

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.

Thanks :)

Lovettalovich answered 7/8, 2013 at 10:38 Comment(2)
It is impossible to do what you ask. Php runs server-side. You can accomplish what you want with javascript that runs on user's browser.Shela
Yes. I understand Php is server-side. That's why I'm having the problem. As I show above, I did use javascript to get the dimensions and post it to PHP. It works, but it causes the problem of running all the php again (which on my site causes double outputs, wacky results, etc). Maybe there's a better way to post it from javascript to PHP than what I'm doing? Thanks..Lovettalovich
M
9

How about having your document ready AJAX request send to a separate PHP document, then include that in the head on page load. That way, you can have whatever specific HTML you want loaded put straight into the body when ready.

For example:

<head>
<script>
$(document).ready( function() {
    var height = $(window).height();
    var width = $(window).width();
    $.ajax({
        url: 'body.php',
        type: 'post',
        data: { 'width' : width, 'height' : height, 'recordSize' : 'true' },
        success: function(response) {
            $("body").html(response);
        }
    });
});
</script>
</head>
<body></body>

And then your body.php file would look something like:

<?php
if(isset($_POST['recordSize'])) {
$height = $_POST['height'];
$width = $_POST['width'];
$_SESSION['screen_height'] = $height;
$_SESSION['screen_width'] = $width;
//Any html you want returned in here

If you then didn't want that JS function to run every page load, just encase the whole thing in a <?php if(isset($_SESSION['screen_height'])) { //JS function } ?>

I'm not 100% sure what you were intending to do with the dimensions once you have them, so I apologise if my answer is a little vague, but by doing it this way the page only sets the saved dimensions on the first visit this browsing session, and it doesn't have to redirect, so I hope it's at least a little helpful :)

Manus answered 7/8, 2013 at 12:54 Comment(4)
The site logs visitors, what they do, etc. This question is because they want to also include in their record the screen and viewport dimensions of every visitor. Sorry wasn't clear... I played with your solution. I still get the double-run problem. I'm probably missing something? The script will go on around 100 pages on the site. It records every visitor to every page. Problem is the script runs twice, so every visitor is double-counted... ThanksLovettalovich
Do you still have some code submitting to the page? The code I suggested should be entirely asynchronous but it doesn't stop anything that still refreshes/submits on the current page from running. I did notice that I had missed out a closing }); on the AJAX call but that shouldn't affect page refreshingManus
Your idea worked: split it into a separate PHP document, then run the JS function only when screen_height isset. What a big work-around, just to get user's viewport dimensions into a database without causing other problems... Thanks for your help :)Lovettalovich
Yeah it is a bit of a workaround but getting client side information to server side always has a bit of faffing required!Manus
B
1

I think it's better to ask yourself: What do you want to do with the width and height? And look if there are other ways to accomplish that goal. You cannot get the user his screen width and height using PHP because it runs server-side.

So this data is never available on the first load.

You could submit the data using AJAX and then make the changes to the page using JavaScript. Then the next page reload the data is, when stored, server-sided available.

Bekah answered 7/8, 2013 at 10:44 Comment(2)
I understand Php is server-side. That's why I'm having the problem. The javascript code above posts it to php, and it would be fine if that were all.. but all the php then runs again when it posts. Maybe "first load" isn't the right word to use? I just mean that I want the PHP to not run twice, and to not have to use a jump page/refresh page.Lovettalovich
Create a seperate PHP file that stores the data. A page refresh is not avoidable I think. You could maybe refresh sections of your page with AJAX, if needed.Bekah

© 2022 - 2024 — McMap. All rights reserved.