TwitterFacebook

Tech Note: Using Media Queries With PHP

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

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
‘Outside Agitators’ Worsening Unrest in Ferguson, Mo., Residents Say
In a pattern that has played out night after night since 18-year-old Michael Brown was shot and killed Aug. 9 by Ferguson Police Officer Darren Wilson, nonviolent gatherings are followed by looting and riots, tear gas and rubber bullets ...

11 hours, 15 minutes ago
Views: 125 • Comments: 0
Tweets: 0 • Rating: 1
FemNaziBitch
For Victims of Domestic Violence, Each Day Carries Danger - Metro - the Boston Globe
When you live with an abuser, everything is a weapon. In their hands, innocent objects like ice-cube trays and checkerboards and apples and pillows become ways to inflict suffering, to demand submission. radio&bull; dog&bull; steak knife&bull; sneaker&bull; apple&bull; box ...

11 hours, 33 minutes ago
Views: 101 • Comments: 0
Tweets: 0 • Rating: 0
CriticalDragon1177
The Japan Times - Can Japan show the West how to live peacefully with Islam?
Nicolas Gattig on Islam in Japan. Off course ignorant Islamophobic wingnut Bryan Fischer Is happy they "don't" allow Muslims in Japan. Man is he going to be upset if he reads this. Long ago, in another life, I went to ...

1 day, 7 hours ago
Views: 329 • Comments: 3
Tweets: 2 • Rating: 3
Rightwingconspirator
Photography Is Not A Crime
re: #274 NJDhockeyfan re: #262 NJDhockeyfan re: #259 jaunte So lets keep this in mind for Ferguson-Shoot an unarmed man in the head under color of authority and leave town with your identity protected. Take a picture of a protest, ...

1 day, 8 hours ago
Views: 201 • Comments: 0
Tweets: 0 • Rating: 1
Laughing Gas
Scumbag “HBD believer” claims Michael Brown charged officer
WARNING: LINK TO HATE SITE He links to some ijreview, a right wing site: This guy makes me sick.

1 day, 10 hours ago
Views: 397 • Comments: 6
Tweets: 1 • Rating: 0
BadExampleMan
“Growth” and Some Jellyfish
This piece was basically just to use up some scraps I had sitting around. I liked the way the frit lace turned out but I didn't really have a use for it. I've been on a jellyfish kick lately. This ...

5 days ago
Views: 270 • Comments: 0
Tweets: 1 • Rating: 2
Pie-onist Overlord
Police Investigating Whether Rabbi’s Miami Killing a Hate Crime
More: Police Investigating Whether Rabbi's Miami Killing a Hate Crime (Reuters) - Police in Miami investigating the killing of a 60-year-old Orthodox rabbi over the weekend said on Monday they haven't yet decided whether the shooting was a hate crime. ...

1 week, 1 day ago
Views: 501 • Comments: 0
Tweets: 1 • Rating: 1
Romantic Heretic
The War Photo No One Would Publish
An interesting story on a photograph taken during Desert Storm that no news outlet in the US would publish. It is one of those photos that stares straight at the horror of war. It's hideous, stomach turning...and something that should ...

1 week, 3 days ago
Views: 1,188 • Comments: 8
Tweets: 4 • Rating: 7
Bubblehead II
Live web Cams on Oahu, Hawaii
Couple of live web cams for Oahu. H/T to explore.org Turtle Bay - East and Ehukai Beach, Oahu Sunrise isn't for a couple more hours so there isn't much to see. But should get interesting after daybreak.

1 week, 5 days ago
Views: 650 • Comments: 0
Tweets: 3 • Rating: 5
 Frank says:

Lord have mercy on the people in England for the terrible food these people must eat. And Lord have mercy on the fate of this movie and God bless the mind of the man in the street.