how to get screen width through php? [duplicate]

十年热恋 提交于 2019-12-02 12:24:48

问题


Hi i know that php is server side thing... but i want know how to get user screen width through php. i search on the net, they says i have to use javascript and php together. but i don't how to make work. please tell me in simplest way to get the screen width of the user through php. if it can done through javascript only then tell me the way to pass the width variable of the javascript to the php variable in integer format(not string).

please show me codes to do it... i'm really messed up in all this... thanks :)


回答1:


Not possible with complete php you might need to use javascript too Anyway try this

<?php
session_start();
if(isset($_SESSION['screen_width']) AND isset($_SESSION['screen_height'])){
    echo 'User resolution: ' . $_SESSION['screen_width'] . 'x' . $_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>';
}
?>



回答2:


I am not sure, But It may help you

    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script>
    var width = $(window).width();
    //This is ajax code which will send width to your php page in the screenWidth variable
    $.ajax({
    url: "example.php", //this will be your php page 
    data : {screenwidth:width} 
    }).done(function() {
    $(this).addClass("done");
    });
    </script>

    //example.php code is here :
    <?php
    echo $width = $_REQUEST['screenwidth'];
    ?>



回答3:


I agree that it is a bad idea to rely on screen width from the client but here, for your edification:

javascript:

    if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.open("GET","set_screen_width.php?s="+screen.width,false);
xmlhttp.send();

If you execute this script on loading the page, it will check the screen width and send it to your php file which needs to be something like:

    <?PHP
session_start();
$_SESSION['screen']['width']=$_GET['s'];
?>

All your other PHP pages can then access the $_SESSION variable vis:

<?PHP
session_start();
$screen_width=$_SESSION['screen']['width'];

etc...

It is better not to try to send HTML that will only look good in one screen width. You can, but it's a losing game. You just don't know what the client is going to do with it. Suppose, for instance, that they have low vision and like to use a larger font.



来源:https://stackoverflow.com/questions/16996551/how-to-get-screen-width-through-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!