Tech Note: Using Media Queries With PHP

Communicating across the client-server divide
LGF • Views: 13,861

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:

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

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

Open Thread (w/ Heartbleed News)

LGF • Views: 11,272

I’ll need to put the LGF web server into maintenance mode for a short time, probably within the next 3 hours, in order to complete some work cleaning up the mess created by this nasty Heartbleed apocalypse you might have heard about. The good news is that our servers are completely patched against the bug, and our SSL certificate has been revoked, reissued and reinstalled. When all the necessary back-end stuff is complete, I’ll be asking all registered LGF users to change their passwords ASAP, but hold off until I give the signal.

It’s a really interesting mental exercise to exhaustively go though a server and identify everything that might be a security problem if it’s in the server’s memory. That’s what makes Heartbleed insidious — it essentially gives an attacker access to the server’s entire memory (in 64K chunks, with repeated requests), and when encrypted data is in RAM it’s in decrypted form. Basically, the exploit based on this OpenSSL bug makes everything that should be private on a server easily accessible if it’s ever read into RAM, and it leaves not a single trace of its filthy work.

In the meantime, here’s an open thread as I get things set up so this maintenance time can be as short as possible.

UPDATE at 4/9/14 6:01:18 pm

We went into and out of maintenance mode so fast you may not have noticed it, but LGF’s servers are now fully protected from the Heartbleed monster. Time to change your LGF passwords, folks.

And if you’re not already using 1Password, you really should look into it. It makes password management 271% less stressful.

Monday Night Open

When the going gets weird, the weird get going
LGF • Views: 13,302

Here’s a simple, unadorned open thread, on what can only be called a rather slow news day, as I continue going through the site and making things mobile-friendly. Next up on the list: LGF Spy mode, our live-streaming view of comment threads. In fact, it’s almost ready to launch…

LGF Mobile Updates: Upload Photos Directly From Your Phone

And much more
LGF • Views: 13,403

I got some good work done on the mobile version today:

  • The popup Image Library that lets you search, view, insert, and tweet your previously uploaded images is now fully mobile-friendly.
  • You can now upload images directly from your smart phone, by tapping the "Upload Image" button. You can choose to take a photo and immediately upload it, or pick a photo from your phone's camera roll.
  • There's now a button at the top of the screen that lets you switch to the full-size "Desktop Version," and a button to let you switch back as well.
  • If you tap an author's name in the Featured or Recent Pages lists, it now pops up the list of their last 5 Pages; on mobile devices this popup dialog has a big red X to let you close it.
  • The "live updating" features of LGF are now enabled on mobile phones, so you can see the count of new comments in a thread and other little things that update continuously for signed-in users.
  • Lots and lots of little tweaks to make things look better.

LGF Mobile Version Update: LGF Pages Now Mobile-Ready

And now, posting on the go
LGF • Views: 9,508

I still have a lot of work to do to completely finish the Marvelous LGF Mobile Makeover, but I’m pleased to report that you can now post to LGF Pages from your mobile phone, in a form optimized for the small screen.

All the features of our LGF Pages window work in the mobile version as well; the Image Library still looks rough and needs work at this point, but it’s fully functional.

There are some limitations to using the LGF Pages bookmarklet in the mobile version of Safari; the best way is to save the bookmarklet in your browser’s Favorites. If you tap that Favorite while looking at a web page you want to post, the LGF Pages window will open in a new tab with the title and URL filled in. Unfortunately, we can’t grab the selected text on the page in mobile browsers, so you’ll have to old-school copy-and-paste. Also, when you tap the bookmarklet, it can look like nothing happened, because it doesn’t automatically switch to the new tab; you have to manually switch to it.

You can now also edit your LGF Pages with a smartphone after posting them, by tapping the little pencil icon at the bottom right of your post.

Out in the woods
Or in the city
It’s all the same to me
When I’m drivin’ free
The world’s my home
When I’m mobile

^ back to top ^


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!

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



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.

Last updated: 2014-03-07 2:19 pm PST

LGF User's Guide
Recent Pages
Randall Gross
Putin Decrements Our Peace Dividend: U.S. Ground Troops Being Deployed To Poland
If you were looking to the wind down of the Afghan war as creating a potential peace dividend, that's now unlikely due to Putin's nationalistic moves on the Ukraine. Poland and the United States will announce next week the deployment of U.S. ground forces to Poland as part of an expansion of NATO presence in Central and Eastern Europe in response to events in ...

1 hour, 20 minutes ago
Views: 58 • Comments: 0
Tweets: 0 • Rating: 0
Denmark Shows the World How to Stop Mass Medicating Animals
COPENHAGAN, Denmark -- Michael Nielsen unlocks the door to his pig factory. He doffs his jacket, pants and muddy boots and zips on white coveralls. Then he steps into the maze-like complex housing several thousand pigs. From the birthing room -- where one enormous sow has just delivered 22 squirming piglets -- to the insemination stalls where the next generation is in the ...

12 hours, 32 minutes ago
Views: 85 • Comments: 0
Tweets: 0 • Rating: 0
Live now - 2014 Rip Curl Pro Bells Beach - ASP World Tour
More: 2014 Rip Curl Pro Bells Beach - ASP Iconic Bells Beach in Victoria, Australia once again hosts the world's best surfers for the 41st running of the Bells Beach Contest. New feature in this broadcast: drone cam!

15 hours, 16 minutes ago
Views: 124 • Comments: 0
Tweets: 3 • Rating: 0
Russ Campbell’s Blog: Fiscal Conservatism Seems Alive and Well in Ottawa: 8,900 Public Service Jobs to Be Cut
When Con&shy;ser&shy;v&shy;a&shy;tives un&shy;der Stephen Harper took of&shy;fice in 2006, I was dis&shy;ap&shy;pointed at how much they re&shy;sem&shy;bled their pre&shy;de&shy;ces&shy;sors when it came to their pen&shy;chant for in&shy;creas&shy;ing the size of gov&shy;ern&shy;ment. More: Russ Campbell's Blog: Fiscal Conservatism Seems Alive and Well in Ottawa: 8,900 Public Service Jobs to Be Cut

19 hours, 2 minutes ago
Views: 96 • Comments: 1
Tweets: 0 • Rating: 0
Skip Intro
Why the Temperature of the Yellow Sea Is a Big Deal, and Other Questions About the South Korean Ferry Disaster
The boat ran into trouble several dozen miles from Jindo, an island that sticks out of South Korea's southwestern corner like a little toe. Jindo is surrounded by a group of even smaller islands that are slightly farther afield from the mainland. The ferry was curving around those small islands at the time it issued a distress call. What caused the disaster? We ...

20 hours, 10 minutes ago
Views: 273 • Comments: 3
Tweets: 24 • Rating: 0
Bystander Effect, or Why This Week Has Been Really Scary
And if you have a friend or loved one who's survived an assault, here's a short list of things you should and shouldn't do to help out. Because if I've learned anything over the past few days, it's that watching someone you care for go through something like this can make you feel unbelievably helpless. But, in spite of that feeling, there are ...

23 hours, 50 minutes ago
Views: 196 • Comments: 1
Tweets: 1 • Rating: 0
Idle Drifter
Calgary stabbings: How knife crime in Canada can cause ‘moral panic’
What Calgary police chief Rick Hanson called the "worst mass murder" in the city's history didn't end at the barrel of a gun. Instead, the 22-year-old suspect identified on Tuesday as Matthew de Grood is accused of entering the kitchen at a house party, taking "a large knife" and using it to fatally stab four men and one woman, all of whom were students ...

2 days, 6 hours ago
Views: 202 • Comments: 4
Tweets: 0 • Rating: 0
New York Electoral College: State Joins National Popular Vote Interstate Compact.
Ben Mathis-Lilley, Slate: New York Electoral College: State Joins National Popular Vote Interstate Compact. Instead of pushing for a Constitutional amendment, which would have to be ratified in 38 states, advocates ask individual state legislatures to pass an agreement: that they'll pledge all their presidential electors to the winner of the national popular vote as soon as enough other states pass the law to ...

2 days, 13 hours ago
Views: 214 • Comments: 7
Tweets: 0 • Rating: 1
Political Atheist
The Insane History of Rockets at Jet Propulsion Laboratories
The Rocket Boys In the late 1930s, a group of Caltech graduate students were booted off campus after blowing up (part of!) their building during a rocket test gone awry. Unwilling to give up on the joy of semi-controlled explosions, the students and a few of their friends headed into the San Gabriel Mountains. They picked a deserted gully -- Arroyo Seco -- ...

3 days, 10 hours ago
Views: 242 • Comments: 0
Tweets: 0 • Rating: 2
Drug Companies Want Your Money
Two thematically-related stories on the BBC at the moment: UK drug company Glaxo 'paid bribes to Polish doctors' UK drug company GlaxoSmithKline is facing a criminal investigation in Poland for allegedly bribing doctors, BBC Panorama has discovered. Tamiflu: Millions wasted on flu drug, claims major report Hundreds of millions of pounds may have been wasted on a drug for flu that works no better ...

3 days, 16 hours ago
Views: 261 • Comments: 0
Tweets: 8 • Rating: 0
 Frank says:

The first hyphen in MAH-JUH-REEN could be used for erotic gratification by a very desparate stenographer. -- Sydney australia, 1974, second night. on Mystery box III