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

后端 未结 2 801
谎友^
谎友^ 2021-01-03 03:01

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.

相关标签:
2条回答
  • 2021-01-03 03:13

    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 :)

    0 讨论(0)
  • 2021-01-03 03:24

    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.

    0 讨论(0)
提交回复
热议问题