TwitterFacebook

Tech Note: Using Media Queries With PHP

Communicating across the client-server divide
LGF • Views: 15,393

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

<script>
if (matchMedia && window.matchMedia('(min-device-width: 320px) and (max-device-width: 480px)').matches) {
	document.cookie = 'smartPhone=1; path=/';
}
</script>

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:

<?php
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:
Detect Mobile Browsers - Open Source Mobile Phone Detection
Using window.matchMedia to Do Media Queries in JavaScript - Mozilla Hacks - the Web Developer Blog

^ back to top ^

TwitterFacebook

Turn off all ads for a full year by subscribing!
For about 33 cents a day (per month) or 22 cents a day (per year), our subscription option turns off all advertisements at LGF!
Read more...

► LGF Headlines

  • Loading...

► Tweeted Articles

  • Loading...

► Tweeted Pages

  • Loading...

► Top 10 Comments

  • Loading...

► Bottom Comments

  • Loading...

► Recent Comments

  • Loading...

► Tools/Info

► Tag Cloud

► Contact

You must have Javascript enabled to use the contact form.
Your email:

Subject:

Message:


Messages may be published unless you request otherwise.
Tech Note:
Using the Contact Form
LGF Pages

This button leads to the main index of LGF Pages, our user-submitted articles. You can post your own LGF Pages simply by registering a free account with us.

Create a Page

This 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: 2014-03-07 2:19 pm PST

LGF User's Guide
Recent Pages
Randall Gross
Kansas City, Kansas, Abortion Clinic Closes
One of four remaining clinics in Kansas that provide abortions has closed because its doctor and manager have retired. The Aid For Women clinic in Kansas City, Kansas, closed Saturday and is referring patients to three other clinics in ...

16 hours, 27 minutes ago
Views: 211 • Comments: 0
Tweets: 8 • Rating: 1
Skip Intro
Outside Money Drives a Deluge of Political Ads
WASHINGTON -- An explosion of spending on political advertising on television -- set to break $2 billion in congressional races, with overall spots up nearly 70 percent since the 2010 midterm election -- is accelerating the rise of moneyed ...

16 hours, 33 minutes ago
Views: 157 • Comments: 1
Tweets: 4 • Rating: 3
Rightwingconspirator
Washington, D.C., Handgun Carry Ban Is Ruled Unconstitutional
I agree. Bans are not an option. Jurisdictions like DC will just have to deal with the fact that regulation is the path. Bans don't work. Bans are illegal and unwise. It's simple. we as a society have chosen to ...

1 day, 12 hours ago
Views: 420 • Comments: 74
Tweets: 0 • Rating: 5
Romantic Heretic
Preventing Poverty Not Allowed As A Goal for Charity
The Canada Revenue Agency (Canada's equivalent of the IRS) has told OXFAM Canada that it cannot list 'preventing poverty' as a goal, only 'alleviating' it. The reason is "Relieving poverty is charitable, but preventing it is not." This is just ...

3 days, 13 hours ago
Views: 395 • Comments: 11
Tweets: 0 • Rating: 4
FemNaziBitch
Safer Era Tests Wisdom of ‘Broken Windows’ Focus on Minor Crime
While the apparent chokehold fueled much of the initial public outcry, community leaders have begun asking whether focusing police officers so intently on such petty offenses makes sense in a city that is far different and far safer than ...

3 days, 20 hours ago
Views: 315 • Comments: 2
Tweets: 0 • Rating: 1
Mentis Fugit
Frisson
Over at the quirky Riddled blog, I encountered this music video link. I have the album, but I had last listened long ago, and I had forgotten the lyrics. The lengthy, moody intro slowly drew me back thirty five years, ...

6 days, 6 hours ago
Views: 237 • Comments: 0
Tweets: 0 • Rating: 0
BadExampleMan
The painful futility of war
This makes me furious. These men pledged their loyalty to their country and their country betrayed them. It treated them as disposable, throwing their lives away in a war that was premised on lies, that was chosen gleefully, and that ...

1 week ago
Views: 414 • Comments: 0
Tweets: 1 • Rating: 1
MichaelJ
Mick Fanning Wins J-Bay Open 2014
More: MICK FANNING WINS J-BAY OPEN Finals day for the contest was run in perfect Supertubes conditions. Too bad Kelly Slater and Jordy Smith were eliminated in lesser quality surf - it would have been amazing to have both of ...

1 week, 1 day ago
Views: 329 • Comments: 0
Tweets: 0 • Rating: 2
Thrazidun
Paris: Jews Fight Back Against Islamist Mob - Jewish World - News - Arutz Sheva
More: Paris: Jews Fight Back Against Islamist Mob - Jewish World - News - Arutz Sheva

1 week, 3 days ago
Views: 970 • Comments: 5
Tweets: 0 • Rating: 2
GlutenFreeJesus
Gotta love Chicago
Admittedly, I only started following these guys in the past year or two. They have been in the Chicago scene for awhile. And I kick myself after every show for not following them sooner. For any fans of Led Zeppelin, ...

1 week, 3 days ago
Views: 460 • Comments: 0
Tweets: 0 • Rating: 2
 Frank says:

A composer is a guy who goes around forcing his will on unsuspecting air molecules, often with the assistance of unsuspecting musicians.