The following is a guest post by Zachary Brady. Zachary is about to take us on a beginner’s journey using PHP to do some things that us front end developers sometimes need to do. To me, this kind of thing doesn’t make us back end developers, but more resourceful front end developers. Zachary also focuses on PHP here, but the same concepts are available in any back end language.
PHP sometimes gets a bad rap, yet it still persists and flourishes not only within some of the most popular CMSs but also with emerging strategies such as Responsive Design with Server Side Components (RESS). I have found that sprinkling a little PHP into my front-end development workflow strengthens the code and speeds up the development process.
It isn’t very difficult or time consuming to pick up enough basics of PHP to get started including it in your toolkit. Let’s get right into discovering how mixing a little server side script into your front end development can be both easy and rewarding.
Getting Started With Some PHP Basics
If you know your way around the basics of PHP, then by all means jump ahead to the next part. For the rest of us, it may be good to brush up a little.
As a server side language, a PHP file (such as index.php or myAwesomeCatPhotos.php) is processed into HTML by your server before being sent to the browser. For this reason, you must host your PHP files on a server while working with them. This may either be a remote server or a local server which exists on your computer. This is actually fairly simple to set up thanks to software like MAMP. (Starter video here on CSS-Tricks).
One of the great things about PHP is that you can mix it with normal HTML within a PHP file.
The and <code>?>
tags define where you are using PHP in your file. Pro tip: if you find that your pages are turning out blank, first check to make sure that you aren’t missing a closing PHP tag anywhere. The echo function prints whatever follows it directly into the markup. In this case what is being “echoed” is a string with the words “Hello World”. In PHP, ending a statement with a semicolon is mandatory; missing semicolons are another common source of failing scripts. This simple PHP translates into
<code>
<code>
Variables in PHP can be written as $aWord
, $manyWords
, $a_lot_of_numbers
, $a4
, etc. The key ingredient is the $ at the start of the variable name.
<code>
With variables we could write the previous code like this:
<code>
<code>
PHP also has for
loops and if
statements. An if
statement asks a question and performs a task if the question proves to be true and can be coupled with an else
statement which performs a task if the question was false.
<code>
<code>
If $a
is equal to 7 then the first string will be echoed but if $a
is equal to something silly like 5 the second statement will be echoed.
<code>
A for
loop is used to repeat a set of code as long as certain condition is met.
<code>
<code>
This says that we will set a variable called $d
to 0, that we will echo the value of $d
as long as it is below 7, and will increment $d
by one at the end of each iteration. This produces “0123456”.
<code>
We will also be using the function include()
, which takes the relative path of another PHP file, locates the file specified by the path, and includes its contents within the file it is called from.
<code>
There is so much more to PHP than this, but these basics will carry us through the rest of the article. If you are still a bit unsure about PHP I suggest reading ahead first and then brushing up a little more. Seeing these concepts in context may help you better understand them.
<code>
Simple PHP Templating
<code>
You may find that as you create your markup for each page of your project that certain parts repeat themselves. The most commonly repeated parts in a web project are the header and the footer.
<code>
Typically, if we have to change something in the header of our website we would have to manually edit the header in every file in our project. This is where PHP steps up to make our jobs easier. With PHP we can store the markup related to the header of our project in its own file and use the include()
function to add the code to our files. We can of course do the same thing with the footer element and any other snippet we may want to use on multiple pages.
<code>
<code>
In this example header.php and footer.php are stored in a directory called “includes” and are each referenced in the file. Imagine how much development time can be saved with this trick alone.
<code>
Serving Different Files Depending On the Page
<code>
One drawback to serving the same header and footer on every page is that, by default, we have less control of what files are served to the different pages. We may have a JavaScript file for an image slider that we only need on the homepage or a script for form validation on the contact page. Thankfully there’s another simple trick that can help us with this.
<code>
To perform this trick I first need to get the name of the current file and strip the file extension from it.
<code>
<code>
The first line gets the name of the file from the server while the second line strips the file extension from it (the second line is more cosmetic to make your code a little cleaner but I still recommend it). I tend to put this line of code at the very top of my files even before opening my tag; this allows me to use this data for a variety of purposes such as generating class names.
<code>
The second part of this trick, deciding which scripts to serve for which page goes into the footer before the closing body tag. We’ll use an if/else statement combination to check to see if the current page is the contact page. If it is a script tag referencing my contact.min.js file is echoed, if not then we’ll echo the global.min.js file.
<code>
';
} else {
echo '<script src="js/global.min.js"></script>';
}
?>
This technique can be used with any type of external file you may want to include. I even like to use Grunt to organize my JavaScript into page or section specific files and then use this technique.
A Little RESS Can Go a Long Way
We can go even further with the example above and use a similar technique to serve different files depending on their device context. This is a very simple example of a RESS solution. RESS, Responsive Design with Server Side Components, just means that you are mixing a little bit of server side logic into your responsive design toolkit in order to do awesome things like shaving off some page weight.
For this we’ll need a PHP library called Mobile Detect, which provides an easy way to discover what type of device your users are using. Include the library in your project somewhere, I like to put it in a “scripts” directory, and then use the require_once
function to include it. You will also have to initiate an instance of the Mobile_Detect
class which I like to do right after the include in my header file.
<code>
Now I can use an if/else pair in my footer to decide whether or not the user is using a mobile device and serve up the appropriate JavaScript file. NOTE: Because Mobile Detect views tablets as a mobile device I’m also checking to make sure the device is not a tablet.
<code>
isMobile() && !$detect->isTablet()) {
echo '<script src="js/global-mobile.min.js"></script>';
} else{
echo '<script src="js/global.min.js"></script>';
}
?>
<code>
Using this technique we can craft JavaScript more appropriate for a mobile experience and ignore all that extra page weight that may come from the large-screen related JavaScript.
<code>
Automatic Markup Patterns
<code>
You may find yourself with certain markup patterns that may not share the same content but look extremely similar to one another. A common situation may be displaying a group of images that belong to the same gallery object. Luckiliy, Lara Schenck recently showed such a solution in a wonderful talk she gave at the Smashing Conference NYC Jam Session.
<code>
// Function to print images
function printGalleryItem($path, $alt) {
echo '
';
}
// Loop through image directory and printGalleryItem markup for each
function printGallery($dir, $alt) {
echo '
';
}
<code>
In PHP, as in other languages, it is possible to create your own custom functions to make it easier to reuse your code.
<code>
The first function, printGalleryItem()
, takes a relative path to an image and text for its alt tag and echos an image tag with a div container. The second function, printGallery()
, takes the relative path to a directory containing images and a string to be used for the images’ alt tags. The function first echos a container for the gallery and then uses a version of the for loop called foreach to cycle through an array of image paths acquired by the glob function and apply them to our printGalleryItem()
function. The foreach function is very useful when you need to cycle through an array of variables and due something to with the values of each one.
<code>
There’s some more advanced concepts that I’m only paying lip service to in this example. For now understanding what these functions do and how they can help with your production is enough. Though it may be good to look further into the foreach
and glob
functions when you get a chance as well. Try making some functions of your own to automate some of the more redundant aspects of your markup.
<code>
This Is Only the Tip of the Iceberg
<code>
There’s a whole world of possibilities of what you can do with a little bit of PHP in your development. Most of the most useful code snippets are quite easy to understand as well and the more you expose yourself to PHP the easier it will become. Doing a little bit of logic on the server before sending a page to the browser can save you development time, give your code a little more robustness, and even lighten up your pages.
<code>
The techniques mentioned in this article should be a good starting point for you whether you’re new to PHP or just new to using PHP in this way. I highly suggest doing a little bit more digging of course and never be afraid to experiment either; broken code can always be fixed. And hey, you might just find that you love yourself some PHP in the end.
I don’t think PHP should be used for front-end things like mobile detection. We have media queries for this. PHP might be useful for server-side tempting, however. Node.js might be a better technology to get into as it’s not a new language to front-end devs and it has better performance.
I agree, anything that changes the page depending on the device should be done front-end, or else… caching will mess you up. If you detect a mobile device and some server caches that response, all requests going through that server will see the mobile version.
You could argue that device detection shouldn’t really be a factor. Rather, it should be things like performance, screen real-estate and feature support.
However, a server-side language can manipulate content before it’s rendered for the client. This means you get a consistent result even when the user doesn’t have JavaScript enabled, since you’d probably be using that in the first place to manipulate where things appear on the screen.
I’d argue against Node.js being a better technology for it, though. We’re not talking about massive tasks here, so I wouldn’t imagine performance being an issue. Hosting support for Node might not be available – I know this is certainly true for me where I work. PHP is fairly straight forward for the likes of including a header and a footer as shown in the article.
For nearly all non-interactive elements, you really should try not to use JavaScript to position them. CSS can handle most everything.
As for Node.js, you can get hosting for $5–10/month. Working with JavaScript is quicker than PHP because you don’t need to memorize two languages and you get access to things like Handlebars. As Martin said, simple templating with PHP is not a great pattern.
That’s true for some things. But in local testing, I have used PHP to basically design areas specific to mobile and others for desktop.
//Check if user is on a PHONE
if ( $detect -> isMobile( ) ) {
//A simple css only Carousel with small images
include(“simple-slider.php”); }
else{
//A carousel with large images
include(“fancy-slider.php”); }
So mobile users get a really simple Carousel with small images and no javascript. While desktop users get the one with all the bells and whistles.
#FACEPALM
Wow. I hadn’t thought of server caching.
Well, it hasn’t been an issue so far. Will decide to change if/ when it does.
It might be fair to say you’re letting some personal bias get in the way here–sure, node.js is technically JavaScript, but the conventions are entirely different than those a front-end dev will use interacting with any of the multitude of JS libraries intended for DOM manipulation and interaction.
That node.js is “just JavaScript” seems like a misguided selling point. To your point later in the thread–every developer should learn more than one language. As a person who works with both PHP and JavaScript on a near daily basis, to imply that you have to “memorize” a language to be able to use it also seems a bit presumptuous. Who has the spec for any language memorized? This is what documentation is for.
On a side note, PHP has templating languages (I don’t know where you heard otherwise). See Twig for example, as others have mentioned.
Just my two cents!
Googling things like “javascript indexof php equivalent” only wastes time when it could be saved using Node.js
I never said that PHP did not have templating languages. Hogan (like Mustache) is good, but Handlebars.js is better.
While you can use media queries and JS to change existing content, I agree with TJ that server-side languages have the advantage of manipulating and changing content before they hit the client-side. I’ve used PHP mobile detection on almost every site I’ve built without much issue.
And as far as caching goes, this can easily be solved by creating separate caches for mobile and desktop. For WordPress users, W3 Total Cache has an easy option for this: https://wordpress.org/plugins/w3-total-cache/
@Ben B,
The W3 plugin creates a mobile cache by sniffing UA strings. It can be difficult to stay up-to-date with what UA strings are/not mobile, making that method of cache control unreliable. You would have to synchronize those settings with the UA strings in your php code.
Regardless, the act of creating two separate caches is too non-DRY for my tastes. I think the best course is to educate your designer and client on the mobile-first mentality, and strive to serve the same content to all devices.
This article gives a good example of PHP device detection: http://www.smashingmagazine.com/2014/07/22/responsive-web-design-should-not-be-your-only-mobile-strategy/
Auto-correct got me on “server-side TEMPLATING” in my original comment above. Sorry about that.
Very disappointed. Expected backend based LESS/SASS compiling or similar “Frontend Tasks” like this one:
https://github.com/kriswallsmith/assetic
“There’s a whole world of possibilities of what you can do with a little bit of PHP in your development. ”
I think like the author is feeling very smart about this, as it gives only advice on obvious stuff.
These “techniques” are rather old. Nothing a FE developer hasn’t dealt with when editing a WordPress Site or similar.
What’s worse is that these bad practices are supported by css-tricks.
How long have you been a front end developer or dealing with the web in general?
Sure, PHP isn’t good for everything. Maybe it doesn’t even excel at anything. But it works. On virtually every platform out there.
So there is really no reason to hate it, and it has some really great uses, like making templates, user accounts, etc.
If anyone is “feeling very smart”, it would be you. I hate to break it to you, but while the various CSS flavors may be good for a lot of things, they all still boil down to CSS. In other words, you aren’t going to get any backend stuff done with them like talking to SQL and the like.
If I were you, I wouldn’t start critiquing relative experts (not saying I am one of them, I am still learning as well) until I had some more experience.
To “Simple PHP Templating”
I rather use a Templating engine like Smarty/Twig/Dwoo. Because it is often hard to decouple backend and frontend stuff.
Templating engines make sure, that you are seperating the backend from the frontend stuff
echo “The variable $a is currently 7.”;
In this case, because you are using double-quotes, you will not print:
Instead you will print
Probably should change that ;)
I noticed that while editing, and left it in there because I figured someone would point it out and it would be a good learning experience. It’s not technically wrong, it’s just that variable gets interpolated =).
Gotcha ;)
More Pro Tips / clarifications:
This is incorrect. Variable names must start with a
$
, followed by a letter or underscore (not a number), and then zero or more letters, numbers, or underscores. The example$a-lot-of-numbers
would be interpreted as$a
subtractlot
subtractof
subtractnumbers
, which, as you might imagine, probably makes no sense and will result in errors.Blank pages are actually the result of a parse error when PHP is configured not to display errors to the webpage (which is good for “live” sites). Missing closing tags or semicolons are common syntax errors, but so are mismatched brackets and many other things. Instead of trying to “guess” what is wrong, find the PHP error log on your server (usually in the directory above your web root, or ask you web host). PHP’s error messages are actually very straightforward once you get used to reading them, and doing so will cut out tons of debugging time (and frustration). If you don’t understand an error message, just copy+paste it to google.
PHP and HTML (css, javascript, etc.) do not actually “mix”. This might seem like a minor distinction, but it is very important for understanding what is actually going on. When you change a file’s extension to
.php
, it is no longer an HTML file. Even if it is only HTML markup, with no PHP tags. PHP runs the file, on your server, and outputs the results (including inline HTML) to the browser. For example, in a PHP script, this:Does exactly the same thing as
include
(andrequire
, etc.) use filesystem paths to find the file you want, which are a very common source of confusion. Keep in mind that filesystem paths are not URLs. Filesystem paths are on your server; URLs are on the internet. In many cases, it looks like there is a direct relationship between the two, but this is not actually the case.As above, I would discourage trying to “detect” mobile browsers from the server. This is browser sniffing (mainly via the User-Agent header), which is generally frowned upon because it is fragile, quickly outdated, and sometimes just wrong.
Depending on the kind of the content, server-side browser sniffing is fine.
I’d also add the tip:
which saves quite some typing.
Well, I’m not telling you that you can’t use it, or that there will never be a situation where it is appropriate. I can’t think of one, however. In my experience, browser sniffing is a lot of work to implement and is difficult to maintain. Even when done “correctly,” it tends to create more opportunities for problems than it solves. In contrast, an approach like capability detection is less work, eminently maintainable, and is less error-prone.
There are many resources discussing this subject on the internet. css-tricks has an article which is a good place to start.
Regarding the use of
<?= $stuff ?>
instead of<?php echo $stuff; ?>
, I agree. There is the caveat that, in PHP versions less than 5.4, this feature might not be available (depending on PHP configuration settings). Just something to be aware of.You can’t use dashes in variable names in php ($a-lot-of-numbers is not valid). PHP interprets dashes as minus symbols and attempts to subtract lot from $a.
You can use underscores however:
http://www.php.net/manual/en/language.variables.basics.php
A lot of smarties are commenting here, and then when you go check their porfolio you laugh so hard you end up wetting your pants
Keep in mind, with many of us so called smarties, we don’t have time to keep up our portfolios because we are too busy working. My site is 3 years out of date and portfolio is about 1 year out of date.
Further, as is my case, some of us are not designers (sadly I just can’t do it) so our portfolios are a display of our designers as much as ourselves.
Although looking at the comments so far, I couldn’t find a reasonable example of responsive design in any of them. So I would agree with you, it is odd to comment about best responsive design practices without producing responsive designs.
I am as much a back end developer as a front end developer, and I would never use php for mobile detection.
To me its just wrong and is impossible to not serve someone the wrong code.
Its far better to serve someone a hidden element (as long as it doesn’t contain images), rather than hope the detection worked as expected.
However, I haven’t made a responsive site with a drastically different design for mobile vs full size, but isn’t that the point?
The only time this can get questionable or muddled is trying to get a cms to write code for your clients that adheres to the standards of responsive design. Otherwise, use css as much as possible and then use javascript when css can’t quite cut it or to improve user experience.
The back end should not be used for device detection.
Check out my company website: http://www.suits-sandals.com. For the desktop and “tablet” devises I’m using Javascript feature detection to serve up an HTML5 video on the homepage if its supported. However, for a mobile context even serving the Javascript for the detection of these feature didn’t make sense.
Now, if as Scott Fennell points out, my server sniffing fails nothing will really break. Instead the user will just see the “loading” icon and the site header; that’s enough to get the user into the site.
Server side sniffing has made sense for a number of my projects. Not all but a lot of them. As will any technology though, its always best to apply it in a way that won’t hinder critical content or usability.
And ’bout troll!n’, some comments are so lame I can’t help myself.
All my apologeezzzzzzz
Honestly man, although you put yourself in a bad light by cursing at people online, I agree with your basic point. People tend to be very dogmatic about server-side sniffing. It’s way more common to hear people denounce it than it is to hear them explain the reasons for their position.
(meaning, I agree that being dogmatic about server-side sniffing is a bad thing — but that doesn’t make it a good idea to do it, as I explained above)
Wow, lots of drama around this one. How about we agree to disagree and simply say “It depends” for all of these techniques? Everything in here could be right for your circumstances, or it could be completely wrong. Let’s not confuse our individual lenses for everyone else’s.
That said, nice roundup, Chris! Most of these techniques won’t be useful in my particular circumstance, but they’re still good to know about.
Exactly, for most of my websites, and how I’m using these techniques, it makes sense. Trust me, I’d avoid them if they didn’t. But yeah, context matters.
I just finished a new project with the help of Twig (php template engine), and I have to say that it saved me a lot of time. The fact that I keep my content seperated from my markup, be able to loop through an array, include, using snippet html etc. is just really awesome! And you can integrate it immediately in wordpress using the Timber plugin. Oh, and to make a build version of the site, use php’s output buffering in combination with grunt or gulp.
basename accepts a second parameter
While I haven’t used PHP for mobile device detection I have used it in ways similar to assetic (Thanks for sharing that Martin). The amount of performance I squeezed by coupling all my JS files into a single file helped performance so much. We built an entire Angular app that loaded 1 single file for all the JS. We could have made it smarter sure, but it’s amazing what a difference that does compared to getting 40+ JS files in a large application. We made this completely transparent to other front end developers, all they had to do was add the file to an include file (no different to having to add the tag) and it was included in the combined file. Sure debugging the live version could get messy, but you should be using the development environment for that anyway.
I understand what you’re doing, and I would have to say that serving a single combined php file is faster than over 40 smaller scripts. However, you’re losing the benefits of browser caching by combining them with php.
You would be much better off combining them in a build stage with grunt or some other task runner. Then you also have the option of precompressing the file in order to reduce load on the server and make the file size even smaller. Also, this gives you the ability to use source maps to greatly ease debugging. The best part is that you just drop a new js file into the source directory and grunt takes care of it for you and rebuilds the combined file whenever you edit one of the sources.
@JacobPeters, I agree 100% with that statement. The only problem is that I’ve been burned just this week with people complaining that an upgrade to the system wasn’t working. I found out that the HTML templates and even some of the JS files were not refreshing on their browser (Even after a CTRL-F5). Sure it eventually sorted itself out, but it was frustrating receiving a bunch of support calls that were unnecessary.
I suppose using grunt with some versioning on files would certainly solve that. And trust me, I’ve known for a while I need to look into that. Reality unfortunately makes you choose between getting work done that you get paid for or getting infrastructure stuff done. I’m sure I’ll get a slow down at some point that will let me spend a few days investigating and implementing a better build/deployment strategy.
Thanks for the reply though!
I pull double duty. Both front end and back. Mostly back end. I recently did exactly this with mobile detect on 4 projects. By the fifth I was too annoyed by the fact that you can only properly test on a real device or simulator or with a good UA spoofer plugin. I refactored everything I was using Mobile Detect for to client side code and I prefer it.
This article is about what I took part to the RESS
http://www.cotonti.mobi/page.php?al=Mobile_web_Slots
This is my article on the detector for mobiles
http://www.cotonti.mobi/page.php?al=model_style_css
HTML and RES is compatible hard task. I applied a known CMF. CMF for processing spent about 4 years
Isnt’ there already some “media” attribute for css link to do that? although I heard not all devices support them =\ I really don’t like mixing front end and backend, only if to redirect mobiles to mobile website, others to normal
In theory I agree that a little SS logic can be helpful and is not a bad option in certain cases. But in general I feel the benefits are not large enough to support this in everyday production.
Interesting idea and good way to learn a little PHP though!
The one big problem with this is, that this will only work on a PHP server. I’d recommend a approach with a templating language (jade, haml etc. ) and a build system (grunt , glup etc.). This way you get HTML which you can use everywhere.
Thanks for posting this Chris. I am just starting to look into PHP so this will come in very handy.
Great tutorial to start with PHP.