使用PHP获取屏幕分辨率

问题描述 投票:42回答:20

我需要找到访问我网站的用户屏幕的屏幕分辨率?

php server client resolution detect
20个回答
53
投票

你不能用纯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');
});

PHP(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"));
}
?>

所有这些都是非常基本但它应该让你到处找。通常屏幕分辨率不是你真正想要的。您可能对实际浏览器的视图端口的大小更感兴趣,因为这实际上是页面呈现的位置...


0
投票

唯一的方法是使用javascript,然后获取javascript发布到你的PHP(如果你真的需要res服务器端)。然而,如果它们关闭javascript,它将完全落在它的脸上。


0
投票

JS:

$.ajax({
    url: "ajax.php",
    type: "POST",
    data: "width=" + $("body").width(),
    success: function(msg) {

        return true;
    }
});

ajax.php

if(!empty($_POST['width']))
    $width = (int)$_POST['width'];

0
投票

这可以使用cookie轻松完成。此方法允许页面根据屏幕高度和宽度(或浏览器视图端口高度和宽度值)检查存储的cookie值,如果它们不同,它将重置cookie并重新加载页面。代码需要允许用户首选项。如果关闭持久性cookie,请使用会话cookie。如果这不起作用,您必须使用默认设置。

  1. Javascript:检查是否设置了高度和宽度cookie
  2. Javascript:如果设置,请检查screen.height&screen.width(或任何您想要的)是否与cookie的当前值匹配
  3. Javascript:如果未设置cookie或与当前值不匹配,则:a。 Javascript:创建名为(例如)'shw'的持久性或会话cookie到当前screen.height和screen.width的值。 湾Javascript:使用window.location.reload()重定向到SELF。重新加载时,它将跳过第3步。
  4. PHP:$ _COOKIE ['shw']包含值。
  5. 继续使用PHP

例如,我正在使用网络上的一些常见cookie功能。确保setCookie返回正确的值。我把这个代码放在head标签之后。显然该函数应该在一个源文件中。

<head>
<script src="/include/cookielib.js"></script>
<script type=text/javascript>
function setScreenHWCookie() {
    // Function to set persistant (default) or session cookie with screen ht & width
    // Returns true if cookie matches screen ht & width or if valid cookie created
    // Returns false if cannot create a cookies.
    var ok  = getCookie( "shw");
    var shw_value = screen.height+"px:"+screen.width+"px";
    if ( ! ok || ok != shw_value ) {
        var expires = 7 // days
        var ok = setCookie( "shw", shw_value, expires)
        if ( ok == "" ) {
            // not possible to set persistent cookie
            expires = 0
            ok = setCookie( "shw", shw_value, expires)
            if ( ok == "" ) return false // not possible to set session cookie
        }
        window.location.reload();
    }
    return true;
}
setScreenHWCookie();
</script>
....
<?php
if( isset($_COOKIE["shw"])) {
    $hw_values = $_COOKIE["shw"];
}

0
投票

快速的答案是否定的,那么你可能会问为什么我不能用PHP做到这一点。好的,这是一个更长的答案。 PHP是一种服务器端脚本语言,因此与特定客户端的类型无关。然后你可能会问“为什么我可以从php获取浏览器代理?”,这就是因为该信息是在请求服务器时使用初始HTTP头发送的。因此,如果您希望客户端信息不是通过HTTP标头发送的,那么您必须使用客户端脚本语言(如javascript)。


-1
投票

在PHP中,没有标准的方法来获取此信息。但是,如果您使用的是第三方解决方案,则可能。 51Degrees用于PHP的设备检测器具有您需要的属性:

为您提供用户屏幕的宽度和高度(以像素为单位)。要使用这些属性,您需要从sourceforge下载检测器。然后,您需要在文件/文件中包含以下2行,以便检测屏幕高度和宽度:

<?php
require_once 'path/to/core/51Degrees.php';
require_once 'path/to/core/51Degrees_usage.php';
?>

其中path / to / core是从sourceforge下载的'Core'目录的路径。最后,要使用属性:

<?php
echo $_51d['ScreenPixelsHeight']; //Output screen height.
echo $_51d['ScreenPixelsWidth']; //Output screen width.
?>

请记住,当无法识别设备时,这些变量可能会包含“未知”值。


-1
投票

解决方案:制作可扩展的网页设计...(我们应该说适当的网页设计)格式化应该在客户端完成,我确实希望信息传递到服务器但信息仍然有用(每行有多少对象)交易)但仍然网页设计应该是流动的,因此每个行元素不应该放入表中,除非它是一个实际的表(并且数据将扩展到它的单个单元格)如果你使用div你可以将每个元素堆叠在一起并且你的窗户应该在正确的位置“打破”这一行。 (只需要适当的CSS)


-1
投票

PHP仅适用于服务器端,而不适用于用户主机。使用JavaScript或jQuery获取此信息并通过AJAX或URL发送(?x = 1024&y = 640)。


-1
投票

您可以使用前端的JS在cookie中设置窗口宽度,您可以在PHP中获取它:

<script type="text/javascript">
   document.cookie = 'window_width='+window.innerWidth+'; expires=Fri, 3 Aug 2901 20:47:11 UTC; path=/';
</script>

<?PHP
    $_COOKIE['window_width'];
?>

-1
投票

最简单的方法

<?php 
//-- you can modified it like you want

echo $width = "<script>document.write(screen.width);</script>";
echo $height = "<script>document.write(screen.height);</script>";

?>

-3
投票
<script type="text/javascript">

if(screen.width <= 699){
    <?php $screen = 'mobile';?>
}else{
    <?php $screen = 'default';?>
}

</script>

<?php echo $screen; ?> 

25
投票

直接使用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>';
}
?>

19
投票

PHP是服务器端语言 - 它仅在服务器上执行,并且生成的程序输出被发送到客户端。因此,没有“客户端屏幕”信息可用。

也就是说,您可以让客户通过JavaScript告诉您他们的屏幕分辨率。写一个小小脚本给你发送screen.width和screen.height - 可能是通过AJAX,或者更有可能找到它的初始“跳转页面”,然后重定向到http://example.net/index.php?size=AxB

虽然以用户身份发言,但我更倾向于设计一个网站以流畅地处理任何屏幕分辨率。我浏览不同大小的窗口,大多数都没有最大化。


4
投票

使用JavaScript(screen.widthscreen.height IIRC,但我可能错了,有一段时间没有完成JS)。 PHP无法做到。


4
投票

我发现在我的PHP内部使用CSS我的PHP为我做了伎俩。

<?php             
    echo '<h2 media="screen and (max-width: 480px)">'; 
    echo 'My headline';
    echo '</h2>'; 

    echo '<h1 media="screen and (min-width: 481px)">'; 
    echo 'My headline';
    echo '</h1>'; 

    ?>

如果屏幕为480px或更小,这将输出较小尺寸的标题。所以不需要使用JS或类似的传递任何变量。


2
投票

您可以尝试RESS(RESponsive设计+服务器端组件),请参阅本教程:

http://www.lukew.com/ff/entry.asp?1392


1
投票

我不认为你可以纯粹用PHP检测屏幕大小,但你可以检测用户代理..

<?php
    if ( stristr($ua, "Mobile" )) {
        $DEVICE_TYPE="MOBILE";
    }

    if (isset($DEVICE_TYPE) and $DEVICE_TYPE=="MOBILE") {
        echo '<link rel="stylesheet" href="/css/mobile.css" />'
    }
?>

这是一个更详细的脚本链接:PHP Mobile Detect


1
投票

这是一个非常简单的过程。是的,你无法在PHP中获得宽度和高度。确实,JQuery可以提供屏幕的宽度和高度。首先去https://github.com/carhartl/jquery-cookie并获取jquery.cookie.js。这是使用php获取屏幕宽度和高度的示例:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Test</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
        <script src="js/jquery.cookie.js"></script>
        <script type=text/javascript>
            function setScreenHWCookie() {
                $.cookie('sw',screen.width);
                $.cookie('sh',screen.height);
                return true;
            }
            setScreenHWCookie();
        </script>
    </head>
    <body>
        <h1>Using jquery.cookie.js to store screen height and width</h1>
    <?php
         if(isset($_COOKIE['sw'])) { echo "Screen width: ".$_COOKIE['sw']."<br/>";}
         if(isset($_COOKIE['sh'])) { echo "Screen height: ".$_COOKIE['sh']."<br/>";}
    ?>
    </body>
    </html>

我有一个你可以执行的测试:http://rw-wrd.net/test.php


1
投票

Fully Working Example

我找不到一个实际工作的PHP示例“无形”(没有URL参数)将客户端屏幕大小和其他属性返回到服务器端PHP,所以我把这个例子放在一起。

JS填充并提交一个隐藏的表单(由PHP从JS属性数组编写脚本),POSTing自身(PHP中现在提供的数据)并返回表中的数据。

(在“几个”浏览器中测试过。)

<!DOCTYPE html>
<html>
<head>
    <title>*Client Info*</title>
    <style>table,tr{border:2px solid gold;border-collapse:collapse;}td{padding:5px;}</style>
</head>

<body>
<?php
  $clientProps=array('screen.width','screen.height','window.innerWidth','window.innerHeight', 
    'window.outerWidth','window.outerHeight','screen.colorDepth','screen.pixelDepth');

  if(! isset($_POST['screenheight'])){

    echo "Loading...<form method='POST' id='data' style='display:none'>";
    foreach($clientProps as $p) {  //create hidden form
      echo "<input type='text' id='".str_replace('.','',$p)."' name='".str_replace('.','',$p)."'>";
    }
    echo "<input type='submit'></form>";

    echo "<script>";
    foreach($clientProps as $p) {  //populate hidden form with screen/window info
      echo "document.getElementById('" . str_replace('.','',$p) . "').value = $p;";
    }
    echo "document.forms.namedItem('data').submit();"; //submit form
    echo "</script>";

  }else{

    echo "<table>";
    foreach($clientProps as $p) {   //create output table
      echo "<tr><td>".ucwords(str_replace('.',' ',$p)).":</td><td>".$_POST[str_replace('.','',$p)]."</td></tr>";
    }
    echo "</table>";
  }
?>
<script>
    window.history.replaceState(null,null); //avoid form warning if user clicks refresh
</script>
</body>
</html>

返回的数据是extract'd变量。例如:

  • window.innerWidth$windowinnerWidth返回
© www.soinside.com 2019 - 2024. All rights reserved.