56

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

ashleedawg
  • 17,207
  • 5
  • 53
  • 80
Elitmiar
  • 30,202
  • 72
  • 172
  • 224
  • 9
    This is done via JavaScript, not PHP. PHP is only executed server-side. While sniffing a user's screen resolution though, please keep in mind that not all users browse full screen! – sjstrutt Oct 01 '09 at 15:03
  • A CSS way to render the design dep on size: http://stackoverflow.com/questions/19186243/javascript-to-get-screen-width-in-php-variable – Breaking not so bad Jul 31 '14 at 10:06
  • Use JavaScript to get this info and send via AJAX – Elyor Aug 13 '15 at 11:29
  • Similar question with **alternative options**: [Can php detect client browser monitor size/resolution?](https://stackoverflow.com/q/892089/8112776) – ashleedawg May 01 '19 at 06:44
  • 2
    This really should be doable via PHP (I know it currently can't). Saying that it shouldn't because PHP is server-side is ignoring all the other client information we DO get via $_REQUEST, such as HTTP_USER_AGENT. Why can't we have another field with the browsers view port size? – Sophivorus Jun 11 '20 at 21:55

22 Answers22

65

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

KyleFarris
  • 16,408
  • 4
  • 40
  • 40
  • Kyle have you found a way of obtaining the browser viewing port dimensions? – a coder Sep 18 '12 at 17:33
  • @KyleFarris ... i am not so good on jquery and json.. how it will be code is that like bellow `$(function() { $.post('header.php', { width: 800px }, function(json) { if(json.outcome == 'success') { header-800px.php // do something with the knowledge possibly? } else { header.php; } },'json'); });` – Accore LTD Nov 26 '13 at 03:32
  • I don't agree with you about view's resolution, however, the answer is great! I guess this info may used for stats and banning. I would more prefer user agent and ip for that. Screen resolution is also good! – volter9 May 08 '14 at 02:58
  • What is the significance of "some_script.php"? Does that have to be the name of the page loading the script? Can it be generic for all pages? – WilliamK Jan 16 '18 at 21:24
  • A ***working*** answer would be even better. What am I supposed to do something with?? – ashleedawg May 01 '19 at 00:20
  • nm, I made one [here](https://stackoverflow.com/a/55933429/8112776) :-) – ashleedawg May 01 '19 at 08:23
30

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>';
}
?>
  • Good solution - implemented and works great. I also pulled http_user_agent (even though it's not always filled/accurate). Wish there was a way to grab the actual browser viewing port size. (as opposed to the screen res). – a coder Sep 18 '12 at 17:31
  • I like this solution. Simple - redirect to a page with size in the url. For anyone reading this - you can get the browser viewport size - see http://stackoverflow.com/questions/8794338 which says (with jquery) use the .height() and .width() functions. – Ukuser32 Feb 24 '16 at 17:02
  • Good solution but please can you provide us with one using cookie instead of sessions ? – John Max Aug 04 '16 at 16:53
  • What's the easiest way to do this invisibly to the user? (eg, no URL paramaters etc) – ashleedawg May 01 '19 at 00:21
  • This is actually pretty ingenious! – santa May 25 '19 at 20:03
  • It's working but always redirects to /index.php on first user entry. – Frostbourn Sep 03 '20 at 07:40
19

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.

Adam Wright
  • 47,483
  • 11
  • 126
  • 149
  • 2
    +1 for the detailed explanations, and not maximizing your browser windows. My browser windows are usually around 800 pixels wide; web pages that resize themselves based on my screen resolution are the bane of my existence! – Alex Barrett Oct 01 '09 at 15:06
6

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.

delp
  • 561
  • 8
  • 18
5

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

Rich R
  • 261
  • 3
  • 12
3

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

Cat Plus Plus
  • 113,388
  • 26
  • 185
  • 215
3

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>";

?>
WebSon
  • 325
  • 1
  • 9
  • I wonder why S.O users downvote very good answers like this one. Thank you so much, your answer provides direct access through PHP to the width and height of the screen and I have tested it even on old mobile devices. Thank you – John Max Oct 02 '20 at 18:17
  • Foolish. You're already on the DOM. You're not going anywhere with that code. Unless you figured out how to use server side code on a client's machine. If you know how to do that then I stand corrected - You're amazing! :) – Ricalsin Feb 25 '21 at 18:56
3

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
QHarr
  • 72,711
  • 10
  • 44
  • 81
ashleedawg
  • 17,207
  • 5
  • 53
  • 80
  • Thx for the complete PHP code. That's just copy'npaste and works great. – LeO Jun 10 '19 at 19:45
  • Great example to follow. Much appreciated. – Neil_Tinkerer Sep 09 '20 at 16:53
  • This is the best PHP version I have seen so far. No complication nor javascript conflict BUT PLEASE how to retrieve exactly the width in php variable? – John Max Oct 02 '20 at 18:08
  • "**the data now available in PHP**" It's only 'available' to php if it's on a server. For that to happen then your code would need to submit those DOM properties back up to the server via an ajax call. Or, you could finish off your submit routine with a form method and get it that way but you haven't shown that and things are already quite messy. All you have done here is printed some strings of text using php and then dropped it on the DOM. – Ricalsin Feb 25 '21 at 19:11
2

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

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

benske
  • 3,592
  • 4
  • 22
  • 22
1

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

davidcondrey
  • 29,530
  • 14
  • 105
  • 129
1

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'];
?>
Faisal Rehman
  • 142
  • 1
  • 5
1

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

PSK1337
  • 39
  • 7
0

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.

UK-AL
  • 538
  • 4
  • 8
0

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

eylay
  • 1,543
  • 3
  • 19
  • 43
IProblemFactory
  • 8,777
  • 5
  • 44
  • 62
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'];
krówek
  • 44
  • 4
0

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"];
}
0

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.

0

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!";
}
  • Although this does not respond with a screen resolution it does detect whether the end user is using a mobile device or not and that served my purposes. I just want to deliver a different set of menu choices to my website visitors based on their choice of device and this worked perfectly for me. Thanks. – Michael Moriarty Aug 07 '20 at 20:57
0

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 );
R. Yaghoobi
  • 161
  • 1
  • 3
-1

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.

Mike
  • 134
  • 8
-1

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)

Pere Noel
  • 9
  • 1
-3
<script type="text/javascript">

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

</script>

<?php echo $screen; ?> 
Laurel
  • 5,522
  • 11
  • 26
  • 49
  • You cannot set a php variable in a JavaScript. – japetko Oct 13 '16 at 10:50
  • To explain this genious: First php executes on the server side ie. before reaching the browser, while javascript executes after reaching the browser. – Sumeet Oct 14 '16 at 06:44