A Sprinkling of PHP: Server-Side Techniques to Help with Front End Tasks

Published by Guest Author

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.

<div>
  <?php 
    echo "Hello World";
  ?>
</div>

The <?php and ?> 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

<div>
  Hello World
</div>

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.

With variables we could write the previous code like this:

<div>
  <?php 
    $whatDoYouSay = "Hello World";
    echo $whatDoYouSay;
  ?>
</div>

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.

<?php
  if ($a == 7) {
    echo "The variable $a is currently 7.";
  } else {
    echo "The variable $a is something else other than 7 and should feel ashamed of itself.";
  }
?>

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.

A for loop is used to repeat a set of code as long as certain condition is met.

<?php
  for ($d = 0; $d<7; $d++) {
    echo $d;
  }
?>

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".

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.

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.

Simple PHP Templating

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.

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.

<?php include("includes/header.php"); ?>

<div>All of the main content of the page which should be more than just this.</div>

<?php include("includes/footer.php"); ?>

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.

Serving Different Files Depending On the Page

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.

To perform this trick I first need to get the name of the current file and strip the file extension from it.

<?php
  $file = basename($_SERVER['PHP_SELF']);
  $pagename = str_replace(".php","",$file); 
?>

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 <html> tag; this allows me to use this data for a variety of purposes such as generating class names.

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.

<?php
  if ($pagename == 'contact') {
    echo '<script src="js/contact.min.js"></script>';
  } 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.

<?php
  require_once 'scripts/Mobile_Detect.php';
  $detect = new Mobile_Detect;
?>

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.

	<?php
  if (isset($detect) && $detect->isMobile() && !$detect->isTablet()) {
    echo '<script src="js/global-mobile.min.js"></script>';
  } else{ 
    echo '<script src="js/global.min.js"></script>';
  }
?>

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.

Automatic Markup Patterns

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.

// Function to print images
function printGalleryItem($path, $alt) {
  echo '<div class="gallery__item">';
    echo '<img src="' . $path . '" alt="' . $alt . '">';
  echo '</div>';
}

// Loop through image directory and printGalleryItem markup for each
function printGallery($dir, $alt) {
  echo '<div class="gallery">';
  $fdir = 'assets/img/galleries/' . $dir . '/*';
  foreach (glob($fdir) as $img_path) {  
    printGalleryItem($img_path, $alt);
  }
  echo '</div>';
}

In PHP, as in other languages, it is possible to create your own custom functions to make it easier to reuse your 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.

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.

This Is Only the Tip of the Iceberg

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.

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.