使用PHP获取屏幕分辨率

发布于 2024-08-06 13:21:12 字数 30 浏览 6 评论 0原文

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(23

已下线请稍等 2024-08-13 13:21:12

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

所有这些都是非常基本的,但它应该能让你有所收获。通常,屏幕分辨率并不是您真正想要的。您可能对实际浏览器视口的大小更感兴趣,因为那实际上是页面渲染的地方......

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

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:

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

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

止于盛夏 2024-08-13 13:21:12

直接使用 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 方法中发送另一个参数的新解决方案(由 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>';
}
?>

Directly with PHP is not possible but...

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

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

New Solution If you need to send another parameter in Get Method (by 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>';
}
?>
拒绝两难 2024-08-13 13:21:12

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

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

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

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.

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

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.

相思故 2024-08-13 13:21:12

最简单的方法

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

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

?>

Easiest way

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

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

?>
姐不稀罕 2024-08-13 13:21:12

我发现在 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>'; 

    ?>

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

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

<?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.

平生欢 2024-08-13 13:21:12

您可以像下面这样检查:

if(strstr(strtolower($_SERVER['HTTP_USER_AGENT']), 'mobile') || strstr(strtolower($_SERVER['HTTP_USER_AGENT']), 'android')) {
   echo "mobile web browser!";
} else {
echo "web browser!";
}

You can check it like below:

if(strstr(strtolower($_SERVER['HTTP_USER_AGENT']), 'mobile') || strstr(strtolower($_SERVER['HTTP_USER_AGENT']), 'android')) {
   echo "mobile web browser!";
} else {
echo "web browser!";
}
手长情犹 2024-08-13 13:21:12

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

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-cookie and get jquery.cookie.js. Here is example using php to get the screen width and height:

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

十秒萌定你 2024-08-13 13:21:12

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

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

与风相奔跑 2024-08-13 13:21:12

完全工作的示例

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

JS 填充并提交一个隐藏表单(由 PHP 从 JS 属性数组编写脚本),POST自身(数据现在在 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 中返回

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.

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.

(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:

  • window.innerWidth is returned in $windowinnerWidth
颜漓半夏 2024-08-13 13:21:12

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

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

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

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

英雄似剑 2024-08-13 13:21:12

您可以在前端使用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'];
?>

You can set window width in cookies using JS in front end and you can get it in 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'];
?>
拔了角的鹿 2024-08-13 13:21:12

我不认为你可以纯粹用 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 移动检测

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

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

酸甜透明夹心 2024-08-13 13:21:12

这是 Javascript 代码:(index.php)

<script>
    var xhttp = new XMLHttpRequest();  
    xhttp.open("POST", "/sqldb.php", true);
    xhttp.send("screensize=",screen.width,screen.height);
</script>

这是 PHP 代码:(sqldb.php)

$data = $_POST['screensize'];
$pdo = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$statement = $pdo->prepare("UPDATE users SET screen= :screen WHERE id = $userid");
$statement->execute(array('screen' => $data));

我希望您知道如何从会话中获取 $userid,
为此,您需要一个数据库,其中包含名为 users 的表,以及 users 内部的名为 screen 的表;=)
问候 KSP

Here is the Javascript Code: (index.php)

<script>
    var xhttp = new XMLHttpRequest();  
    xhttp.open("POST", "/sqldb.php", true);
    xhttp.send("screensize=",screen.width,screen.height);
</script>

Here is the PHP Code: (sqldb.php)

$data = $_POST['screensize'];
$pdo = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$statement = $pdo->prepare("UPDATE users SET screen= :screen WHERE id = $userid");
$statement->execute(array('screen' => $data));

I hope that you know how to get the $userid from the Session,
and for that you need an Database with the Table called users, and an Table inside users called screen ;=)
Regards KSP

冷了相思 2024-08-13 13:21:12

唯一的方法是使用 javascript,然后将 javascript 发布到您的 php(如果您确实需要资源服务器端)。然而,如果他们关闭 JavaScript,这将完全失败。

The only way is to use javascript, then get the javascript to post to it to your php(if you really need there res server side). This will however completly fall flat on its face, if they turn javascript off.

如此安好 2024-08-13 13:21:12

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

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'];
动听の歌 2024-08-13 13:21:12

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

  1. Javascript:检查高度和是否符合要求width cookie set
  2. Javascript:如果设置,则检查 screen.height & screen.width (或任何你想要的)与 cookie
  3. Javascript 的当前值匹配:如果 cookie 未设置或与当前值不匹配,则:
    一个。 Javascript:创建名为(例如)“shw”的持久或会话cookie,以设置当前screen.height &的值。屏幕宽度。
    b. 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"];
}

This can be done easily using cookies. This method allows the page to check the stored cookie values against the screen height and width (or browser view port height and width values), and if they are different it will reset the cookie and reload the page. The code needs to allow for user preferences. If persistant cookies are turned off, use a session cookie. If that doesn't work you have to go with a default setting.

  1. Javascript: Check if height & width cookie set
  2. Javascript: If set, check if screen.height & screen.width (or whatever you want) matches the current value of the cookie
  3. Javascript: If cookie not set or it does not match the current value, then:
    a. Javascript: create persistent or session cookie named (e.g.) 'shw' to value of current screen.height & screen.width.
    b. Javascript: redirect to SELF using window.location.reload(). When it reloads, it will skip the step 3.
  4. PHP: $_COOKIE['shw'] contains values.
  5. Continue with PHP

E.g., I am using some common cookie functions found on the web. Make sure setCookie returns the correct values.
I put this code immediately after the head tag. Obviously the function should be in a a source file.

<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"];
}
小霸王臭丫头 2024-08-13 13:21:12

PHP 只能在服务器端运行,不能在用户主机上运行。使用 JavaScript 或 jQuery 获取此信息并通过 AJAX 或 URL (?x=1024&y=640) 发送。

PHP works only on server side, not on user host. Use JavaScript or jQuery to get this info and send via AJAX or URL (?x=1024&y=640).

水波映月 2024-08-13 13:21:12

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

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.

云巢 2024-08-13 13:21:12

用于获取宽度屏幕或高度屏幕
1- 创建一个 PHP 文件(getwidthscreen.php)并在其中写入以下命令
PHP (getwidthscreen.php)

<div id="widthscreenid"></div>
<script>
document.getElementById("widthscreenid").innerHTML=screen.width;
</script>

2- 通过以下命令通过 cURL 会话获取宽度屏幕
PHP(main.php)

$ch = curl_init( 'http://hostname/getwidthscreen.php' );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
$result = curl_exec( $ch );
print_r($result);
curl_close( $ch );

For get the width screen or the height screen
1- Create a PHP file (getwidthscreen.php) and write the following commands in it
PHP (getwidthscreen.php)

<div id="widthscreenid"></div>
<script>
document.getElementById("widthscreenid").innerHTML=screen.width;
</script>

2- Get the width screen through a cURL session by the following commands
PHP (main.php)

$ch = curl_init( 'http://hostname/getwidthscreen.php' );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
$result = curl_exec( $ch );
print_r($result);
curl_close( $ch );
影子的影子 2024-08-13 13:21:12

好吧,我有另一个想法,因此使用纯 PHP 以非常简单的方式实现 90% 的可能性。我们不会立即知道确切的屏幕分辨率,但我们会找出用户使用的是计算机(更高分辨率)还是手机(更低分辨率),因此我们将能够加载特定数据。
代码示例:

$user_agent = $_SERVER['HTTP_USER_AGENT'];

if (strpos($user_agent, 'Windows') !== false) {
    //PC, high resolution
    //*note for phone is: Windows Phone
} elseif (strpos($user_agent, 'Mac') !== false) {
    //PC, high resolution
} else {
    //mobile, small resolution
   //Android, iOS, Windows Phone, Blackberry OS, Symbian OS, Bada OS, Firefox OS, WebOS, Tizen OS, KaiOS, Sailfish OS, Ubuntu Touch, HarmonyOS, EMUI, OxygenOS, One UI, Magic UI, ColorOS, MiUI, OxygenOS, ZenUI, LG UX, FunTouch OS, Flyme OS, OxygenOS, Samsung One UI, Android One, Android Go, Android TV, Android Auto, Fuchsia OS.
}

那么,完成验证的一个很好的解决方案是抛出 cookie 并使用 PHP 检查数据。

//JS:
function setCookieResolution() {
        // Get screen resolution
        if (!getCookieValue("screen_resolution")) {
            var screenResolution = window.screen.width + "x" + window.screen.height;
            // Create cookie with resolution info
            document.cookie = "screen_resolution=" + screenResolution + ";path=/";
        }
    }
    setCookieResolution();

//PHP:
if (isset($_COOKIE["screen_resolution"])) {
    $currentValue = $_COOKIE["screen_resolution"];//example: 1920x1080
    $parts = explode("x", $currentValue);
    if(count($parts) == 2 && is_numeric($parts[0]) && is_numeric($parts[1])) {
        $width = (int)$parts[0];
        $height = (int)$parts[1];
    } else {
        // handle error
    }
}

Well, I have another idea, thanks to which it is 90% possible in a very simple way using pure PHP. We will not immediately know the exact screen resolution, but we will find out whether the user is using a computer (higher resolution) or a phone (lower resolution) and thanks to this we will be able to load specific data.
Code example:

$user_agent = $_SERVER['HTTP_USER_AGENT'];

if (strpos($user_agent, 'Windows') !== false) {
    //PC, high resolution
    //*note for phone is: Windows Phone
} elseif (strpos($user_agent, 'Mac') !== false) {
    //PC, high resolution
} else {
    //mobile, small resolution
   //Android, iOS, Windows Phone, Blackberry OS, Symbian OS, Bada OS, Firefox OS, WebOS, Tizen OS, KaiOS, Sailfish OS, Ubuntu Touch, HarmonyOS, EMUI, OxygenOS, One UI, Magic UI, ColorOS, MiUI, OxygenOS, ZenUI, LG UX, FunTouch OS, Flyme OS, OxygenOS, Samsung One UI, Android One, Android Go, Android TV, Android Auto, Fuchsia OS.
}

Then, a great solution to complete the verification is to throw a cookie and check the data using PHP.

//JS:
function setCookieResolution() {
        // Get screen resolution
        if (!getCookieValue("screen_resolution")) {
            var screenResolution = window.screen.width + "x" + window.screen.height;
            // Create cookie with resolution info
            document.cookie = "screen_resolution=" + screenResolution + ";path=/";
        }
    }
    setCookieResolution();

//PHP:
if (isset($_COOKIE["screen_resolution"])) {
    $currentValue = $_COOKIE["screen_resolution"];//example: 1920x1080
    $parts = explode("x", $currentValue);
    if(count($parts) == 2 && is_numeric($parts[0]) && is_numeric($parts[1])) {
        $width = (int)$parts[0];
        $height = (int)$parts[1];
    } else {
        // handle error
    }
}
姐不稀罕 2024-08-13 13:21:12

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

  • $_51d['ScreenPixelsHeight']
  • < a href="https://51 Degrees.com/Resources/Property-Dictionary#ScreenPixelsWidth" rel="nofollow">$_51d['ScreenPixelsWidth']

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

<?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.
?>

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

In PHP there is no standard way to get this information. However, it is possible if you are using a 3rd party solution. 51Degrees device detector for PHP has the properties you need:

Gives you Width and Height of user's screen in pixels. In order to use these properties you need to download the detector from sourceforge. Then you need to include the following 2 lines in your file/files where it's necessary to detect screen height and width:

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

Where path/to/core is path to 'Core' directory which you downloaded from sourceforge. Finally, to use the properties:

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

Keep in mind these variables can contain 'Unknown' value some times, when the device could not be identified.

你是暖光i 2024-08-13 13:21:12

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

solution: make scalable web design ... ( our should i say proper web design) formating should be done client side and i did wish the info would be passed down to server but the info is still usefull ( how many object per rows kind of deal ) but still web design should be fluid thus each row elements should not be put into tables unless its an actual table ( and the data will scale to it's individual cells) if you use a div you can stack each elements next to each other and your window should "break" the row at the proper spot. ( just need proper css)

欢你一世 2024-08-13 13:21:12
<script type="text/javascript">

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

</script>

<?php echo $screen; ?> 
<script type="text/javascript">

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

</script>

<?php echo $screen; ?> 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文