Tech Note: Using Media Queries With PHP
One of the major hurdles in a responsive mobile-friendly design is that the code that runs on your server (in our case PHP code) doesn’t have any simple way to get the screen dimensions of the user’s browser.
As a result, many mobile designs for PHP require the use of complicated checks for many different types of mobile devices, which is kludgy from a programming standpoint, and violates the whole ethos of responsive design, in which you program for screen size, not device type. And it runs the risk of breaking in the future as well, like all kludges based on user agents.
After wrestling with it for a while, I’ve come up with something that works for me. It’s not ideal in some ways, but it does let your server-side PHP code respond to a browser’s screen dimensions.
The big caveat is that this little bit of Javascript code must run as the very first thing in the
section of your HTML document, before any other Javascript and preferably before anything else.From the PHP standpoint this has one drawback: if your PHP code needs to do anything specific to mobile devices before sending any output to the browser, you’ll still need to fall back on the messy user agent solution. But any PHP code that runs after this bit of Javascript will be able to respond to the screen size properly.
Here’s the code that goes in the head section:
Here’s how it works: the latest versions of all the major browsers have a Javascript method that duplicates the CSS media query functionality, called “matchMedia.” You pass it the same kind of string you’d use in your CSS code, and it returns a “MediaQueryList” object; the matches property is true or false depending on whether the device matches the media query.
So this little bit of code first makes sure matchMedia exists, then calls the method with a string specifying smartphone-sized devices. If the matches flag is true, it sets a session cookie (expires when you close the browser window) called “smartPhone.” That’s all there is to it.
From that point on in your PHP code, you can simply do something like this to respond to the screen size:
if ($_COOKIE['smartPhone']) {
// do your mobile stuff here
} else {
// do your non-mobile stuff here
}
This code is specifically written for smartphone-sized screens, but it could easily be adapted to support more screen sizes as necessary. I’ve found it very useful in building LGF’s responsive mobile design, so maybe it will come in handy for someone else out there in the Internets.