使用 PHP 获取屏幕分辨率

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1504459/
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-08-25 02:51:22  来源:igfitidea点击:

Getting the screen resolution using PHP

phpserverclientresolutiondetect

提问by Elitmiar

I need to find the screen resolution of a users screen who visits my website?

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

回答by KyleFarris

You can't do it with pure PHP. You must do it with JavaScript. There are several articles written on how to do this.

你不能用纯 PHP 来做到这一点。您必须使用 JavaScript 来完成。有几篇文章介绍了如何做到这一点。

Essentially, you can set a cookie or you can even do some Ajax to send the info to a PHP script. If you use jQuery, you can do it something like this:

本质上,您可以设置 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 (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"));
}
?>

All that is really basic but it should get you somewhere. Normally screen resolution is not what you really want though. You may be more interested in the size of the actual browser's view port since that is actually where the page is rendered...

所有这些都是非常基本的,但它应该可以帮助您找到某个地方。通常屏幕分辨率并不是您真正想要的。您可能对实际浏览器视口的大小更感兴趣,因为这实际上是呈现页面的地方...

回答by Carlos Ricardo Schmitz

Directly with PHP is not possible but...

直接使用 PHP 是不可能的,但是......

I write this simple code to save screen resolution on a PHP session to use on a image gallery.

我编写了这个简单的代码来在 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>';
}
?>

回答by Adam Wright

PHP is a server side language - it's executed on the server only, and the resultant program output is sent to the client. As such, there's no "client screen" information available.

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

That said, you can have the client tell you what their screen resolution is via JavaScript. Write a small scriptlet to send you screen.width and screen.height - possibly via AJAX, or more likely with an initial "jump page" that finds it, then redirects to http://example.net/index.php?size=AxB

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

Though speaking as a user, I'd much prefer you to design a site to fluidly handle any screen resolution. I browse in different sized windows, mostly not maximized.

虽然作为用户发言,但我更希望您设计一个网站来流畅地处理任何屏幕分辨率。我在不同大小的窗口中浏览,大多没有最大化。

回答by delp

I found using CSS inside my html inside my php did the trick for me.

我发现在我的 php 中的 html 中使用 CSS 对我有用。

<?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>'; 

    ?>

This will output a smaller sized headline if the screen is 480px or less. So no need to pass any vars using JS or similar.

如果屏幕为 480 像素或更小,这将输出较小尺寸的标题。因此无需使用 JS 或类似方法传递任何变量。

回答by Rich R

This is a very simple process. Yes, you cannot get the width and height in PHP. It is true that JQuery can provide the screen's width and height. First go to https://github.com/carhartl/jquery-cookieand get jquery.cookie.js. Here is example using php to get the screen width and height:

这是一个非常简单的过程。是的,您无法在 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>

I have a test that you can execute: http://rw-wrd.net/test.php

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

回答by Cat Plus Plus

Use JavaScript (screen.widthand screen.heightIIRC, but I may be wrong, haven't done JS in a while). PHP cannot do it.

使用 JavaScript(screen.widthscreen.heightIIRC,但我可能错了,有一段时间没有使用 JS)。PHP 做不到。

回答by benske

You can try RESS (RESponsive design + Server side components), see this tutorial:

你可以试试RESS(响应式设计+服务器端组件),看这个教程:

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

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

回答by davidcondrey

I don't think you can detect the screen size purely with PHP but you can detect the user-agent..

我不认为你可以纯粹用 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" />'
    }
?>

Here's a link to a more detailed script: PHP Mobile Detect

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

回答by ashleedawg

Fully Working Example

完全有效的例子

I couldn't find an actual working PHP example to "invisibly"(without URL parameters) return client screen size, and other properties, to server-side PHP, so I put this example together.

我找不到一个实际工作的 PHP 示例来“不可见地”(没有 URL 参数)将 client screen size和其他属性返回到服务器端 PHP,因此我将这个示例放在一起。

JS populates and submits a hidden form (scripted by PHP from an array of JS properties), POSTing to itself (the data now available in PHP) and returns the data in a table.

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

(Tested in "several" browsers.)

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

<!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>

The returned data is extract'd into variables. For example:

返回的数据被extract放入变量中。例如:

  • window.innerWidthis returned in $windowinnerWidth
  • window.innerWidth返回 $windowinnerWidth

回答by Kisded Szabi - CodeRevolution

The quick answer is no, then you are probably asking why can't I do that with php. OK here is a longer answer. PHP is a serverside scripting language and therefor has nothing to do with the type of a specific client. Then you might ask "why can I then get the browser agent from php?", thats because that information is sent with the initial HTTP headers upon request to the server. So if you want client information that's not sent with the HTTP header you must you a client scripting language like javascript.

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