使用php获取浏览器宽度 [英] Get browser width using php
问题描述
有没有办法通过PHP获取屏幕大小?我在google上看了一下,并通过javascript找到了一种方法:
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:
<?php
$width = "<script>sw=screen.width;</script>";
$height = "<script>sh=screen.height;</script>";
echo "Width: ".$width." Height: ".$height;
?>
但这不会在$ width或$ 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?
推荐答案
你不能这样做,这是一种方法:
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.
您可能想要使用AJAX。
You may want to use AJAX.
此外,如果有人拒绝会话cookie,这将永远循环,更好测试浏览器是否接受cookie。
Also, if someone refuses sessions cookies, this would loop forever, better test if the browser accepts cookies.
这篇关于使用php获取浏览器宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!