javascript 使用php获取浏览器宽度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23239157/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 00:36:29  来源:igfitidea点击:

Get browser width using php

javascriptphp

提问by bd_person

Is there a way to get the screen size through php? I have had a look on google, and found a way of doing it through javascript as follows:

有没有办法通过php获取屏幕大小?我在 google 上看过,并找到了一种通过 javascript 执行此操作的方法,如下所示:

PHP :

PHP :

 <?php
   $width = "<script>sw=screen.width;</script>"; 
   $height = "<script>sh=screen.height;</script>"; 
   echo "Width&#58; ".$width." Height&#58; ".$height;
 ?>

But this doesn't store anything in $width or $height. is this a good way of going about doing it? or is there another way?

但这不会在 $width 或 $height 中存储任何内容。这是一个很好的方法吗?还是有另一种方式?

回答by Sebastien Kovacs

You cannot get browser width by only using php. PHP is server code.

仅使用 php 无法获得浏览器宽度。PHP 是服务器代码。

Try to look at this. You can use ajax to send (post) browser width in your php code.

试着看看这个。您可以使用 ajax 在您的 php 代码中发送(发布)浏览器宽度。

Hope it helps.

希望能帮助到你。

回答by Lo?c

You can't do that this way, here is a way to do it :

你不能这样做,这是一种方法:

<?php
session_start();
if(isset($_POST['width'])){
   $_SESSION['screen_size'] = array();
   $_SESSION['screen_size']['width'] = intval($_POST['width']);
   $_SESSION['screen_size']['height'] = intval($_POST['height']);
}


if(!isset($_SESSION['screen_size'])){
?>
<html>
<head>
<script>
function getSize(){
document.getElementById('inp_width').value=screen.width;
document.getElementById('inp_height').value=screen.height;
document.getElementById('form_size').submit();
}
</script>
</head>
<body onload='getSize()'>
<form method='post' id='form_size'>
<input type='hidden' name='width' id='inp_width'/>
<input type='hidden' name='height' id='inp_height'/>
</form>
</body>
</html>


<?php
}else{
    var_dump($_SESSION['screen_size']);
}

This is a simple way, and the page will reload the first time.

这是一个简单的方法,页面会在第一次重新加载。

You may want to use AJAX.

您可能想使用 AJAX。

Also, if someone refuses sessions cookies, this would loop forever, better test if the browser accepts cookies.

此外,如果有人拒绝会话 cookie,这将永远循环,更好地测试浏览器是否接受 cookie。