Increase Productivity by Creating PHP Helper Functions

Every workman needs a good toolbox, and web developers are no different. PHP helper functions are designed to speed up and homogenise repetitive tasks, and make your life that much easier. This first tutorial explains how to make link helpers that will improve your methods for adding hyperlinks and mailto links in your web applications.

An Introduction

Yes, there's nothing quite like awesome, time-saving devices that make lives easier. There are many useful tools out there that can improve your workflow, from CSS grids and layouts to fully fledged content management systems and frameworks.

This tutorial, however, is going to delve into the concept of PHP helper functions, and how you can write generalised snippets for your site that you will be able to use over and over. These are functions that both speed and clean up your coding process, so that repetitive tasks can be minimized, and you can spend more of your time worrying about the important things in life... like dinner.

Hyperlink Helpers

One of the most common repetitive tasks we find ourselves having to write is the hyperlink. By creating a helper function for this we can save time whenever we need to write one, remove any chances of syntax errors, and make sure the code is easy to update if files are moved around, or if you are moving a site to a different domain. To begin, we will make a very simple function in a file called helpers.php:

This little baby can be referred to whenever we need to get the full path to a file, and can be referenced over and over during your site development. This is a more useful method than simply calling the domain with the $_SERVER['HTTP_HOST'] method, because it will not change if someone has typed in the domain with or without the "www", and works happily if your site is on a subdomain, for example "http://localhost/my-site".

It is also incredibly useful when moving the site, because all absolute paths will be referring to this single function, so changing the $domain variable to the new domain will change all of your links sitewide, in one single swoop.

Streamline that Code

What we'll aim to do now is to create a new function called "anchor" that will output a compliant, standard string of html complete with a title. Here is an example of what we'd like to output:

So here we have a PHP function being referenced which has two variables being passed along: one for the link, and one for the display text. So now, still in our helpers.php file, we can start writing the new function:

We then get the domain name from the get_domain() function we've already created

Next, we append the $link variable that has been sent to the function.

We then begin to create the output string in a variable called $data, and use the $text variable to double up as both the visible text for the site, as well as the 'title' tag for the link.

Now we can test this out. Create a new file called index.php, in the same folder as this helpers.php file, and type:

require('helpers.php');
echo anchor('new-page.php','New Page');

Here, we've connected the two files with the require() function, and then called the anchor() function, sending two custom variables with it. If you test this in a browser you will see our desired result:

Make it Flexible

This simple function can be useful, but will no doubt become constricting soon enough. We need to add three new features before it becomes truly awesome and flexible; firstly, an option to add custom title tags; secondly, to be able to add CSS rules; and thirdly, an option for it to open in a new window, if need be.

Let's review custom title tags first. Title tags are very important for SEO purposes, and if you don't put them on your links at the moment, I strongly recommend it becomes a habit from now on. This function will help force you into doing so -- actually, as it's a lot easier to add, and if you haven't added one manually, a default copy of the display text will be used instead.

Styling and Target Options

To make sure we can still use this helper even if we need to add custom CSS or target tags, we will now add a part to our function that will read a fourth variable, and output the correct html accordingly.

We need this function to be intelligent enough to see if we want to put in a CSS class, a CSS ID, or a target tag, and we also want to be able to put in multiple options, or a singular option, or no options at all. First, let's modify our anchor function a little:

First up, we add a fourth passing variable, called "$extras." This will contain all of our extra custom options.

Next, we check to see if we are passing an array in this variable. We will be using an array if we're passing multiple extras to the function, for example if we need it to have a CSS ID and a different CSS class for our link.

If it is an array, we will loop through it, and push each item through a new function called "parse_extras." This function will take what extra bits we have entered, and create the correct, corresponding html output.

If $extras is a string, it means we have only passed one rule through; so we can run our new function parse_extras() on the single item. Usefully, the function is_string() returns FALSE if the variable is empty; so with this piece of code, if nothing is passed through $extras, then no code will be run, and it will skip through.

This function makes use of the fact that all our extras will start with a unique identifier. If we're passing a CSS ID, it will begin with a hash (#), if we're passing a CSS class, it will start with a period (.), and if we're passing a target, it will start with an underscore (_).

We can check what the first character of a string is by using the syntax $string[0]. You may be used to using this syntax to retrieve the first item in an array, but it is also a very helpful and quick method for finding specific characters within strings.

Next, we create a new variable, which is our inputted $rule, with the first character chopped off. Now that we have identified what the rule is for, we no longer need it for our html output. This combination of substr() and strlen() is a useful snippet for chopping the first character off a string.

We can now create our $data html output string, ready to return. This method can now be repeated -- firstly for if the $rule is a CSS class, and then if it is an html target tag. It's worth mentioning that we do not need to crop off the first character for the target tag, as html uses the preceding underscore (_), unlike in the CSS rules.

Now that we have created all our necessary functions, we can return to our index.php file and modify our anchor() call.

Mailto Links

Finally, we'll have a look at how to create mailto links in your applications. We'll make a function called mailto() which will be quite similar to the anchor() function, with one major difference: we will be implementing a cipher on the html output so that the email address can't be crawled by spam-spiders, and will keep your client's email addresses secure.

The method we'll use to hide the email address uses the rather awesome str_rot13() PHP function, which simply takes a string and moves all alphabetical characters thirteen letters along, in the alphabet. If you ever went to boy scouts, you probably remember mucking around with such codes, and deciding you were probably going to be a spy when you grow up.

The cipher will output our code in a garbled fashion, and then, using a JavaScript 'antidote' function, we can pull the characters back thirteen places on the alphabet and restore their original meaning. However, as this function is client-side, the 'antidote' only actions, and the text returns to its normal self, when showed on a screen. Thus, spiders, crawlers and spambots, for the most part, won't have a clue what they're reading.

It's probably worth mentioning that there are many methods of hiding mailto links, some a lot more secure than this, some less so. I like to use this method, and have never seen any spam come through to any of my clients because of it. It's worth mentioning too that the JavaScript method itself was developed by Christoph Burgdorfer, and looks like this:

Firstly, we're still passing through four variables to this function, although, for cosmetic purposes, we have renamed the first variable to $email.

Now, we create a new variable with the html output for the mailto link. It's worth noting that we have added a backslash before the quote marks as this string will later appear inside the JavaScript function, and we need to make sure that the quote marks don't confuse it.

Next, we implement the str_rot13() function on the $link variable, so that it is encoded.

We can then create our returning $data variable, which contains the JavaScript ready for outputting.

We put our encoded $link in the middle of all this - ready to be translated.

Now that the JavaScript has been added to our $data variable, the rest of the function will look familiar.

We check to see if a custom title tag has been added, and then we parse our $extras, just as before. Once again, we get our tags closed up...

...and return the data.

We can now use the following syntax in our index.php file to bring up our mailto link:

echo mailto('secret@emailaddress.com','Contact Me');

Or, if we need custom elements, just as before, we can add more variables:

Conclusion

This concludes our first foray into PHP helper functions. This is very much the tip of the iceberg, and, next time, we'll begin reviewing some more complex tools, in the name of form helpers.

Form creation and validation has to be one of my pet peeves when creating them from scratch- there is a lot of repetitive code, painstaking writing, and chances for errors. A series of functions that both output correctly structured forms and check the post data for valid email addresses, passwords, string length, etc, can be a true lifesaver. Ah yes, creating html forms from scratch needs not be so groan-worthy as you previously thought.

If you have any other ideas of what would be really helpful to see in a PHP helper function, be sure to comment your ideas!

Michael J. Watson is a web developer / designer and musician from Manchester UK who runs his own freelance studio called scunby.com. He loves getting his hands dirty in php, playing the violin, CSS, mucking around with jQuery, singing and Photoshop (-ing his girlfriend's face onto dinosaurs).