Determine screensize with php

I have a simple php query to have a random full screen background:

 $sql = "SELECT *
               FROM page_background
       ORDER BY RAND()";

I furthermore use the css3 background property;

#background { 
    background-position: center center;
    background-repeat: no-repeat;
    background-attachment: fixed;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

HTML

<div id="background">
    <img src="/images/page_backgrounds/desktop/<?php echo $page_background['background']; ?>" > 
</div>

Basically this works fine, but as you can see do I use ./desktop/ in the img src to serve default devices. For smaller devices (tablet, smartphone) the img src should be:

<div id="background">
    <img src="/images/page_backgrounds/mobile/<?php echo $page_background['background']; ?>" > 
</div>

Is this possible with php in combination with CSS or should I take a complete different approach?

Thank you in advance

I would think (but am no expert) that whatever calls the PHP code would need to pass through some indication of the device type if it wants the PHP code to be able to use it - otherwise as the PHP runs on the server, how can it know?

http://mobiledetect.net/ might do what you want

You could also have the image defined in css and use media to change which is shown.

@media (min-width: 381px) and (max-width: 479px) {
    #background {
        background: url('/images/page_backgrounds/mobile/image.png'); 
        background-position: center center;
        background-repeat: no-repeat;
        background-attachment: fixed;
        -webkit-background-size: cover;
        -moz-background-size: cover;
        -o-background-size: cover;
        background-size: cover;
    }
}

OR use @media to hide (display:none;) or show a div and have both coded on the page, so based on screen size one or the other is shown.

I have done this in the past as PHP has no idea what the screen resolution is.
In php create an ID and store that with the resolution, (next step),

Use javaScript / jQuery to get the screen resolution and then write to file or database using AJAX.

then query the database to get the resolution into PHP, now you can specify background size for your query.

That is the only way to do it.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.