Tech Note: Using Media Queries With PHP

Communicating across the client-server divide
LGF • Views: 35,924

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.

Also see

Jump to top

Create a PageThis is the LGF Pages posting bookmarklet. To use it, drag this button to your browser's bookmark bar, and title it 'LGF Pages' (or whatever you like). Then browse to a site you want to post, select some text on the page to use for a quote, click the bookmarklet, and the Pages posting window will appear with the title, text, and any embedded video or audio files already filled in, ready to go.
Or... you can just click this button to open the Pages posting window right away.
Last updated: 2016-01-01 10:29 am PST
LGF User's Guide RSS Feeds Tweet

Help support Little Green Footballs!

Subscribe now for ad-free access!Register and sign in to a free LGF account before subscribing, and your ad-free access will be automatically enabled.

Donate with
PayPal
Square Cash Shop at amazon
as an LGF Associate!
Recent PagesClick to refresh
But Her emailzzzzzzz….Here's a great post by Digby regarding the emails pseudo controversy and how it begat President Trump. The big worry is that it will continue -- and there are signs it already is. As long as Russian bots set what ...
Thanos
11 minutes ago
Views: 16 • Comments: 0 • Rating: 0
Tweets: 1 • Share to Facebook
Canada’s Right-Wing Populist, Anti-Immigrant Party Got Crushed Bernier spent the campaign promoting a divisive and exclusionary message that could have easily come from far-right parties such as Germany’s AfD or France’s National Front. He vowed to build a border fence to keep out asylum seekers, stoked ...
Thanos
1 hour, 11 minutes ago
Views: 42 • Comments: 0 • Rating: 0
Tweets: 1 • Share to Facebook
ROXY MUSIC - RE-MAKE/RE-MODEL LIVE at the APOLLO 2001 Cpl593h ROXY MUSIC - RE-MAKE/RE-MODEL LIVE AT THE APOLLO 2001Original by the first Roxy Music Album , the very first song , 1972lyrics below :I tried, but I could not find a wayLooking back, all I did was look awayNext ...
Thanos
2 days, 8 hours ago
Views: 269 • Comments: 0 • Rating: 1
Tweets: 1 • Share to Facebook
“Midnight Picnic Near the Ocean” - Forest BaileyRecorded live at Snaggy Mountain in Burnsville North Carolina. 24-bit Studio Master digital download available at: forestbaileymusic.com Buy/Listen:Spotify: open.spotify.comApple Music: music.apple.com Visit Forest BaileyWebsite: forestbaileymusic.comInstagram: instagram.comFacebook: facebook.comYouTube: youtube.comBandsintown: bandsintown.com
Thanos
3 days, 15 hours ago
Views: 324 • Comments: 0 • Rating: 0
Tweets: 1 • Share to Facebook
#Thegreatpoolpondconversion - 191014After three weeks of meh pictures and invisible progress, we were determined to have something to photograph today. And we were eager to start on the upper shelf. We were close, but not quite there, and we were determined! To ...
DangerMan
1 week ago
Views: 499 • Comments: 0 • Rating: 3
Tweets: 0 • Share to Facebook
Jack Klatt - Highway Lines (Live at Radio Heartland)Jack Klatt performs 'Highway Lines' from his 2019 album, 'It Ain't The Same,' live in the studio of Radio Heartland at The Current.
Thanos
1 week, 2 days ago
Views: 458 • Comments: 0 • Rating: 0
Tweets: 2 • Share to Facebook
Brittany Howard Performing ‘13th Century Metal’ Live on KCRW Brittany Howard's solo debut album Jaime puts her powerhouse vocals on full display. It also takes us front and center to her very personal journey of loss, love and self-discovery. We're thrilled to welcome her back to KCRW to ...
Thanos
1 week, 4 days ago
Views: 659 • Comments: 0 • Rating: 0
Tweets: 1 • Share to Facebook
(15) Rodrigo Y Gabriela - Electric Soul (Live on KEXP) kexp.org presents Rodrigo y Gabriela performing "Electric Soul" live in the KEXP gathering space. Recorded July 14, 2019. Host: Stevie ZoomAudio Engineers: Kessiah Gordon & Kevin SuggsAudio Mixer: David MarchantCameras: Jim Beckmann, Alaia D'Alessandro, Luke Knecht & Justin WIlmoreEditor: ...
Thanos
1 week, 4 days ago
Views: 674 • Comments: 1 • Rating: 1
Tweets: 2 • Share to Facebook
Fresh Air (Remastered) Quicksilver Messenger Service Provided to YouTube by Universal Music Group Fresh Air (Remastered) · Quicksilver Messenger Service Classic Masters ℗ 2001 Capitol Records, LLC Released on: 2007-01-01 Producer: Quicksilver Messenger ServiceStudio Personnel, Mastering Engineer: Robert VosgienComposer: Jesse Oris Farrow Auto-generated by YouTube. ...
Thanos
1 week, 4 days ago
Views: 732 • Comments: 0 • Rating: 2
Tweets: 2 • Share to Facebook
Jon Anderson - Song of SevenFrom the 1980 album "Song of Seven".
Thanos
1 week, 6 days ago
Views: 757 • Comments: 0 • Rating: 0
Tweets: 1 • Share to Facebook