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:
<?php function get_domain() { //the variable $domain can be set to the domain your application is running from. $domain = "http://www.my-site-domain.com/"; return $domain; }
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:
<a href="http://www.my-site-domain.com/new-page.php" title="New Page">New Page</a>
And here is what we’d like to actually be typing:
echo anchor('new-page.php','New Page');
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:
function anchor($link, $text) // 1 { $domain = get_domain(); // 2 $link = $domain . $link; // 3 $data = '<a href="' . $link . '"'; $data .= ' title="' . $text . '"'; //4 $data .= '>'; $data .= $text; //4 $data .= "</a>"; return $data; }
- Here, we set up the function “anchor” with two passing variables.
- 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:
New Page
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.
function anchor($link, $text, $title) //1 { $domain = get_domain(); $link = $domain . $link; $data = '<a href="' . $link . '"'; if ($title) //2 { $data .= ' title="' . $title . '"'; //3 } else { $data .= ' title="' . $text . '"'; //4 } $data.= '>'; $data .= $text; $data .= "</a>"; return $data; }
So here is a modified and improved version of our anchor() function.
- Now we have added a third variable, $title.
- We then run a check to see if a custom title tag has been entered.
- If it has, we add a portion to our output $data string that sets the title tag3.
- If nothing has been entered, it will default the title tag to the display text, $text, as it was before.
Now, if we change our function call in index.php to:
echo anchor('new-page.php','New Page','Custom Title Message!');
We will end up with this satisfactory output:
<a href="http://www.my-site-domain.com/new-page.php" title="Custom Title Message!">New Page</a>
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:
function anchor($link, $text, $title, $extras)//1 { $domain = get_domain(); $link = $domain . $link; $data = '<a href="' . $link . '"'; if ($title) { $data .= ' title="' . $title . '"'; } else { $data .= ' title="' . $text . '"'; } if (is_array($extras))//2 { foreach($extras as $rule)//3 { $data .= parse_extras($rule);//4 } } if (is_string($extras))//5 { $data .= parse_extras($extras);//6 } $data.= '>'; $data .= $text; $data .= "</a>"; return $data; }
- 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. Now we need to make our new function, parse_extras():
- 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.
- 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.
function parse_extras($rule) { if ($rule[0] == '#') //1 { $id = substr($rule,1,strlen($rule)); //2 $data = ' id='' . $id . '''; //3 return $data; } if ($rule[0] == '.') //4 { $class = substr($rule,1,strlen($rule)); $data = ' class='' . $class . '''; return $data; } if ($rule[0] == '_') //5 { $data = ' target='' . $rule . '''; return $data; } }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 (_).
echo anchor('new-page.php','New Page','Custom Title Message!','#special_link');Here we’re passing a CSS ID, and we receive an output of:
<a href="http://www.my-site-domain.com/new-page.php" title="Custom Title Message!" id="special_link">New Page</a>If we were to add an array of extras, in case you wanted it to open in a new window and to have a specific ID and class (unlikely, but worth showing off the flexibility!), we’d do it like this:
$extras = array('#special_id','.special_class','_blank'); echo anchor('new-page.php','New Page','Custom Title Message!',$extras);Here, we pre-establish an array variable called extras, just to keep the code tidy, and then send it along with the anchor() function. This will produce the following output:
<a href="http://www.my-site-domain.com/new-page.php" title="Custom Title Message!" id="special_id" class="special_class" target="_blank">New Page</a>
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:<script type="text/javascript"> document.write("Njrfbzr frperg fcl pbqr".replace(/[a-zA-Z]/g, function(c){return String.fromCharCode((c<="Z"?90:122)>=(c=c.charCodeAt(0)+13)?c:c-26);})); </script>This takes the garbled string “Njrfbzr frperg fcl pbqr” and shifts all the characters, so that the display on your screen looks like:
Awesome secret spy codeHowever, if you review the source code, which is what the spiders and crawlers will see, you will see no mention of this result — thus, it remains hidden. We won’t look at the ins and outs of how this JavaScript works, as this is a PHP tutorial, after all. Instead, we’ll examine how we can implement this in our new mailto() function.
function mailto($email, $text, $title, $extras) //1 { $link = '<a href=\"mailto:' . $email; //2 $link = str_rot13($link); //3 $data = '<script type="text/javascript">document.write("'; //4 $data .= $link; //5 $data .= '".replace(/[a-zA-Z]/g, function(c){return String.fromCharCode((c<="Z"?90:122)>=(c=c.charCodeAt(0)+13)?c:c-26);})); </script>'; $data .= '"'; if ($title) //6 { $data .= ' title="' . $title . '"'; } else { $data .= ' title="' . $text . '"'; } if (is_array($extras)) { foreach($extras as $rule) { $data .= parse_extras($rule); } } if (is_string($extras)) { $data .= parse_extras($extras); } $data .= ">"; $data .= $text; $data .= "</a>"; //7 return $data; //8 }So let’s have a look at what is different here.
echo mailto('secret@emailaddress.com','Contact Me');Or, if we need custom elements, just as before, we can add more variables:
$extras = array('#special_id','.special_class','_blank'); echo mailto('secret@emailaddress.com','Contact me','Contact your good pal Barry.',$extras);