使用 PHP 获取屏幕分辨率
2022-08-30 09:43:30
我需要查找访问我网站的用户屏幕的屏幕分辨率吗?
你不能用纯PHP做到这一点。你必须用JavaScript来做到这一点。有几篇关于如何做到这一点的文章。
从本质上讲,您可以设置一个cookie,甚至可以做一些Ajax将信息发送到PHP脚本。如果你使用jQuery,你可以像这样做:
jquery:
$(function() {
$.post('some_script.php', { width: screen.width, height:screen.height }, function(json) {
if(json.outcome == 'success') {
// do something with the knowledge possibly?
} else {
alert('Unable to let PHP know what the screen resolution is!');
}
},'json');
});
菲律宾比索 (some_script.php)
<?php
// For instance, you can do something like this:
if(isset($_POST['width']) && isset($_POST['height'])) {
$_SESSION['screen_width'] = $_POST['width'];
$_SESSION['screen_height'] = $_POST['height'];
echo json_encode(array('outcome'=>'success'));
} else {
echo json_encode(array('outcome'=>'error','error'=>"Couldn't save dimension info"));
}
?>
所有这些都是非常基本的,但它应该让你有所收获。通常,屏幕分辨率不是您真正想要的。您可能对实际浏览器的视图端口的大小更感兴趣,因为那实际上是页面呈现的位置...
直接使用PHP是不可能的,但是...
我编写此简单代码是为了将屏幕分辨率保存在 PHP 会话上,以便在图像库上使用。
<?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>';
}
?>
新解决方案 如果您需要在 Get Method 中发送另一个参数(由 Guddu Modok 提供)
<?php
session_start();
if(isset($_SESSION['screen_width']) AND isset($_SESSION['screen_height'])){
echo 'User resolution: ' . $_SESSION['screen_width'] . 'x' . $_SESSION['screen_height'];
print_r($_GET);
} else if(isset($_GET['width']) AND isset($_GET['height'])) {
$_SESSION['screen_width'] = $_GET['width'];
$_SESSION['screen_height'] = $_GET['height'];
$x=$_SERVER["REQUEST_URI"];
$parsed = parse_url($x);
$query = $parsed['query'];
parse_str($query, $params);
unset($params['width']);
unset($params['height']);
$string = http_build_query($params);
$domain=$_SERVER['PHP_SELF']."?".$string;
header('Location: ' . $domain);
} else {
$x=$_SERVER["REQUEST_URI"];
$parsed = parse_url($x);
$query = $parsed['query'];
parse_str($query, $params);
unset($params['width']);
unset($params['height']);
$string = http_build_query($params);
$domain=$_SERVER['PHP_SELF']."?".$string;
echo '<script type="text/javascript">window.location = "' . $domain . '&width="+screen.width+"&height="+screen.height;</script>';
}
?>