Tutorial Details
- Program: PHP
- Difficulty: Beginner/Intermediate
- Estimated Completion Time: 30 mins
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.
- 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.
Now we need to make our new function, parse_extras():
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 (_).
Now that we have created all our necessary functions, we can return to our index.php file and modify our anchor() call.
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 code
However, 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.
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:
$extras = array('#special_id','.special_class','_blank');
echo mailto('secret@emailaddress.com','Contact me','Contact your good pal Barry.',$extras);
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!







jQuery Lightbox Evolution only $12.00
Events Calendar Pro - Wordpr ... only $30.00 
What I do for the “extras” option is actually create a function that simply takes an associative array and parses it into name=”value” format. It’s a little more writing when creating them though since you would have to do something like:
$array('class'=>'someclass','id'=>'someid');But it allows complete reusability when dealing with something like form attributes, or image attributes.
Thats exactly what I was thinking, but a lil more so.
You could have an array that has all the attributes you want to set:
array(
‘href’=>’alink.php’,
‘title’=>’a title different than the text’,
‘class’=>’aClassName’,
‘id’=>’theID’,
‘style’=>’some: styles;’
);
and just foreach through the array, and you can still check to make sure they entered a href attribute with “array_key_exists” or not to make an anchor on the page. Doing this would make the function a lil more dynamic.
anchor(‘Link Text’,array(‘href’=>’http://www.google.com’,'class’=>’class names’));
which isnt much longer, and i find it easier to read.
IMO the function signature have to reflect what is expected “from the developer”, so ideally every mandatory attributes (such as href) should be a parameter of the function and optional attributes should be in the $extra parameter.
What I’m the most curious about is the get_domain() function… Why would someone use a function to get a value which is basically a constant ? Usually in my code, I include a initialize.php file at the beginning of the process which “dynamically” sets several constants and DOMAIN is one of those.
looks similar to codeigniter’s helper
Functions that do similar things are probably going to end up looking similar. Care to share your re-invention of the wheel?
http://codeigniter.com/user_guide/helpers/url_helper.html
Same concept. This is not exactly a CI original idea either. I have been using helpers like this since VB script days back in 2002, I think I learn the technique in uni when doing C++. CI is wonderful and takes learnings from many people over a lot of years.
Some great helpers I find are input ones (like in CI):
function inputbuild()
{
$args=func_get_args();
…validate args…
$theReturn=”;
$theReturn.=”;
$theReturn.=makelabel($name, $id);
$theReturn.=”;
$theReturn.=”;
return $theReturn;
}
function makelabel($title, $id)//share the love for other types of inputs
{
return ”.$title.”;
}
This allows for you to make changes really easy. Say you want to add semi-colons to the the labels across the site it is a two second process.
Whoops the HTML got striped!
Right! The tutorial seems inspired by CI. Not a original work.
I think it’s helpful to see the ‘helpers’ concept outside of the CI context. this was a very cool tutorial, IMO. it shows me that I don’t need to rely on a framework for automating these things. it’s a great way to transition someone who really ‘gets’ the CI framework and show them how to actually start programming these things natively. a ‘scaffold’ if you will.
Nice tutorial, the addition of adding css classes and IDs by using the css syntax was a nice touch. One question I had was why did you use a function to return the domain when you could have used a constant? It would give you the same effect, but save you a method call.
I tend to prefer putting domains in a function call, just in case you are setting up an application in a peculiarly located site, in a subdomain, for example. It’s nice to have one simple place where you can type the exact place for your site, and then you can change whenever you have to move. Particularly helpful for moving sites from sandboxes to live, for example.
The anchor() function could be cleaned up/optimized a little bit, but a great start for beginners!
I’d just download the CodeIgniter HTML helper file and include it into your non-CI projects. No point in re-inventing the wheel ‘ey?
But still if you want to create something more custom towards your need then this is great, but I much prefer to do it with associative arrays.
For those of you who aren’t familiar with the HTML helper functions.
Link: http://codeigniter.com/user_guide/helpers/html_helper.html
You need to escape the $title value before you use it. What if I used a quote in it? Same for other entities like &, .
Why not the OOP way?
Why the OOP way?
Why the OOP way?
Just a thought, but wouldn’t it also save time to echo out the output right away rather than return it or at least give an option to return it? I find this a hassle whenever I find myself echoing these functions all the time. Granted, it is only a few extra characters of code, but I find it much easier to write anchor($options) rather than echo anchor($options) every time.
Just my two cents.
Yes you could do this, but if your using it in a template builder or somethign this would break it. Echoing out if your trying to build up a template would end up outputting the result before the template is rendered.
You could offer a fifth option for rendering… but then to use this function it would become more cumbersome… simple example.. if the 5th option was to echo instead of return, and you didnt want to use the 3rd or 4th option, you would call it like this.
anchor(‘test.php’, ‘My Title’, NULL, NULL, TRUE);
that doesnt look easier than…
echo anchor(‘test.php’, ‘My Title’);
at least not to me.
It is usually best practice to *not* echo your output directly from your functions. It makes them more versatile when you return the value instead of echoing it.
I agree. WordPress core functions annoy the hell out of me because a lot of them automatically echo so you have to search for another equivalent function that doesn’t or write your own.
@Darren,
That is true, it’s annoying as hell.
9/10 times I’ve noticed that adding get_ to the front of most functions is the “non-echo” version.
Still a pain.
This is very useful! Going to look at this tonight! See some nice uses for this!
Thnx!
One of my favorites:
function s($num)
{
return 1 == $num ? ” : ‘s’;
}
Okay it ate my example and didn’t post it. This function is for adding an “s” to words that have variable quantities. So you can do something like
echo ‘We found ‘ . $numRows . ‘ item’ . s($numRows) . ‘ in this category.’;
Is your function more complicated than the one that posted?
I would be careful about items with names like “box.” You wouldn’t want to have the incorrect “boxs” show on your site.
That’s easy enough to fix:
function s($num, $add_e=FALSE)
{
$s = $add_e!==FALSE ? ‘es’ : ‘s’;
return $num===1 ? NULL : $s;
}
Or, for more versatility:
function suffix($num, $suffixes = array(”, ‘es’))
{
return $num===1 ? $suffixes[0] : $suffixes[1];
}
Then you could do something like this:
Oops, stripped my last example:
echo “Found “, $numRows, ” entr”, suffix($numRows, array(‘y’, ‘ies’)), ” in this category.”;
And again, CodeIgniter done it better
http://codeigniter.com/user_guide/helpers/inflector_helper.html
Look at plural().
Thanks for the article, building and using helper classes / functions is a great way to speed up development time.
I see one big flaw I see in these helpers is your not setting a default value for the options. If you do not include these then you will get an error if you dont pass something such as the $extras through.
function anchor($link, $text, $title, $extras)
that is how you are declaring this now…
This is how I would declare it
function anchor($link, $text, $title = NULL, $extras = array())//1
you could even set $text to NULL and then check in the script if its empty and if so set $text = $link, then you could call “echo anchor(‘test.php’);” and the text would be mydomain.com/test.php for quick and simple anchors.
As mentioned above, I like to use an array for my attributes because I can set whatever attribute I want. Here is my code.
$value ) :
$attributes .= $prop . '="' . $value . '" ';
endforeach;
}
}
// Build the link
$link = '' . $text . '';
echo $link;
}
anchor('Hello World', array(
'title' => 'My Custom Link',
'href' => 'index.php',
'attr' => array(
'class' => 'link',
'id' => 'special',
'style' => 'color: blue; text-decoration: none;'
)
));
?>
Well darn, here’s a link to snipt.org
http://snipt.org/Spmh
“Increase Productivity by not using PHP but Python”
Wouldn’t it be easier to use a heredoc to write your code rather than just appending?
function anchor($link, $text) // 1
{
$domain = get_domain(); // 2
$link = $domain . $link; // 3
$data = <<<HTML
$text
HTML;
return $data;
}
function anchor($link, $text) // 1{
$domain = get_domain(); // 2
$link = $domain . $link; // 3
$data = <<<HTML
$text
HTML;
return $data;
}
Sorry, forgot to wrap code tags around it.
Sorry to say that i would not have used this approach to making helper methods.
I would prefer the Rails,JQuery or CakePHP way of doing things. Both of the framework uses faking the named parameters . ie my anchor function would have been
function anchor($anchor_text,$link,$options = array(“class”=>”my_class”,”title”=>”hello”)){
extract($options);
return ““.$anchor_text.”“;
}
use extract function to generate dynamic variables on runtime from associative array and then use those on the function.
Rajib
How about a form helpers tutorial next?
That’d be nice.
I never thought of using CI’s helper files. DOY! Thanks Benjamin!
Nice tut,
Umm which ide are you using to write the code in the picture for this tut? and how do you get that background colour?
ta
Hey Josh. Cheers, it’s TextMate with the… erm… Twilight colour scheme. I think it looks sexier than it is, I did a bit of photoshopping to make it look cooler
Also, I don’t really like staring at light colours on a dark background that much, despite how cool it looks. Good for tut thumbnails though!
Here is a form class i wrote about 7 years ago may have some old outdated code but you will get the idea.
The db functions have been able to save heaps of time coding for crud.
<?
/***************************************************************************
* forms.class
* ——————-
* begin : Saturday,10/07/03
* copyright : (C) 2003 Peak Software
* email : chris@peaksoftware.com.au
***************************************************************************/
class forms {
//stores validation javascript
var $validation = "";
//stores form to valide
var $form_name = "";
function forms() {
$validation = "";
}
//Value, display text,table,Select name,seletced item,selectitem=
function query_select($value,$text,$table,$name,$selected=0,$var=0,$custom="") {
$mysql_select = New mysql();
$sql="SELECT $value,$text FROM $table";
$sheader="\n”;
$sfooter=”\n”;
$mysql_select->query($sql);
if ($mysql_select->num_rows() > 0) {
while ($mysql_select->movenext()) {
$svalue= $mysql_select->getfield(0);
$stext= $mysql_select->getfield(1);
if($svalue==$selected){
$sbody=$sbody.”$stext\n”;
}
else
{
$sbody=$sbody.”$stext\n”;
}
}
}
return $sheader.$sbody.$sfooter;
}
function query_select_leadingspace($value,$text,$table,$name) {
$mysql_select = New mysql();
$sql=”SELECT $value,$text FROM $table”;
$sheader=”\n”;
$sfooter=”\n”;
$sbody=”\n”;
$mysql_select->query($sql);
if ($mysql_select->num_rows() > 0) {
while ($mysql_select->movenext()) {
$svalue= $mysql_select->getfield(0);
$stext= $mysql_select->getfield(1);
if($svalue==$selected){
$sbody=$sbody.”$stext\n”;
}
else
{
$sbody=$sbody.”$stext\n”;
}
}
}
return $sheader.$sbody.$sfooter;
}
function checkbox_($name,$value,$checked = false) {
if($checked == $value) {
$checked = “checked=\”checked\”";
} else {
$checked = “”;
}
return “”;
}
//Value, display text,table,Select name,seletced item,selectitem=
function query_select_progress($value,$text,$table,$name,$selected=”",$var=0,$custom=”") {
$mysql_select = New mysql();
$sql=”SELECT id,name,aorder FROM $table order by aorder”;
$sheader=”\n”;
$sfooter=”\n”;
$mysql_select->query($sql);
if ($mysql_select->num_rows() > 0) {
while ($mysql_select->movenext()) {
$svalue= $mysql_select->getfield(‘aorder’);
$stext= $mysql_select->getfield(‘name’);
$sorder= $mysql_select->getfield(‘aorder’);
if($mysql_select->getfield(‘aorder’)==$selected){
$sbody=$sbody.”$sorder-$stext\n”;
}
else
{
$sbody=$sbody.”$sorder-$stext\n”;
}
}
}
return $sheader.$sbody.$sfooter;
}
function manual_select($name,$value,$selected=”") {
$sheader=”\n”;
$sfooter=”\n”;
$temp_text = explode(“,”,$value);
$arrayLength = count($temp_text);
for ($i = 0; $i < $arrayLength; $i++){
if($temp_text[$i]==$selected){
$sbody=$sbody."$temp_text[$i]\n”;
}
else
{
$sbody=$sbody.”$temp_text[$i]\n”;
}
}
return $sheader.$sbody.$sfooter;
}
///Value, display text,table,Select name,seletced item
function query_radio($name,$on,$off,$label1,$label2,$var,$value,$width=150) {
if ($var==$value){
$checked=”checked” ;
$unchecked=”";
}else{
$checked=”" ;
$unchecked=”checked”;
}
$body.=”\n”;
$body.=”$label1\n”;
$body.=”$label2\n”;
$body.=”\n”;
$body.=”\n”;
return $body;
}
function radio($name,$value,$custom=”",$class=”") {
if($class != “”) {
$class = “class=\”$class\”";
}
$body.=”\n”;
return $body;
}
function radioGroup($name=”",$values=array(),$selected=”",$class=”",$custom=”") {
$body = “”;
foreach($values as $val) {
$body .= “”;
if($selected == $val[1]) {
$body.=”";
} else {
$body.=”";
}
$body .= ” ” . $val[0]. “”;
}
return $body;
}
//name, action, method
function form_open($name=”frm”, $action=”", $method=”post” , $custom=”") {
$this->form_name = $name;
return “\n\r”;
}
function form_close() {
return “\n\n” . $this->validation();
}
//name, action, method
function open($name=”frm”, $action=”", $method=”post”, $enctype=”") {
$this->form_name = $name;
if($enctype != “”) {
$enctype = “enctype=\”$enctype\”";
}
return “”;
}
function close() {
return “” . $this->validation();
}
//name, value(multidimensional(text,value)), size class, custom,
function select($name=”select”,$value=array(),$selected=”",$size=1,$class=”",$custom=”") {
$list = “”;
foreach($value as $val) {
if($selected == $val[1]) {
$list .= “”.$val[0].”";
} else {
$list .= “”.$val[0].”";
}
}
$list .= “”;
return $list;
}
//name, class, custom textfield options
function email($name=”email”,$value=”",$custom=”",$class=”",$size=”25″,$maxlength=”50″,$validate=true) {
if($validate==true) {
$this->validation .= “frmvalidator.addValidation(\”$name\”,\”maxlen=50\”);\n\r
frmvalidator.addValidation(\”$name\”,\”req\”);\n\r
frmvalidator.addValidation(\”$name\”,\”email\”);\n\r”;
}
if($class != “”) {
$class = “class=\”$class\”";
}
if($value != “”) {
$value = “value=\”$value\”";
}
return “”;
}
//name, class, custom textfield options
function password($name=”pass”, $class=”", $custom=”",$validate=true,$value = “”) {
if($validate==true) {
$this->validation .= “frmvalidator.addValidation(\”$name\”,\”maxlen=50\”);\n\r
frmvalidator.addValidation(\”$name\”,\”req\”);\n\r”;
}
if($class != “”) {
$class = “class=\”$class\”";
}
return “\n\r”;
}
//name, class, custom textfield options
function button($name=”submit”,$value=”Submit”,$class=”",$custom=”") {
if($class != “”) {
$class = “class=\”$class\”";
}
return “\n\r”;
}
//name, class, custom textfield options
function submit_button($name=”submit”,$value=”Submit”,$class=”",$custom=”") {
if($class != “”) {
$class = “class=\”$class\”";
}
return “\n\r”;
}
//form validation script
function validation() {
if($this->validation != “”) {
$valid = “\n\r
var frmvalidator = new Validator(\”".$this->form_name.”\”);\n\r”;
$valid .= $this->validation;
$valid .= “”;
return $valid;
}
}
//name value
function hidden($name,$value) {
return “\n\r”;
}
//name, value, custom, class
function text_field($name,$value,$custom=”",$class=”",$size=”25″,$maxlength=”25″,$validate=false) {
if($validate==true) {
$this->validation .= “frmvalidator.addValidation(\”$name\”,\”maxlen=$maxlength\”);\n\r
frmvalidator.addValidation(\”$name\”,\”req\”);\n\r”;
}
if($class != “”) {
$class = “class=\”$class\”";
}
return “\n\r”;
}
//name, value, custom, class
function text_area($name,$value,$custom=”",$class=”",$maxlength=255,$cols=40,$rows=5,$validate=false) {
if($validate==true) {
$this->validation .= “frmvalidator.addValidation(\”$name\”,\”maxlen=$maxlength\”);\n\r
frmvalidator.addValidation(\”$name\”,\”req\”);\n\r”;
}
if($class != “”) {
$class = “class=\”$class\”";
}
return “$value\n\r”;
}
//name, value, custom, class
function post_code($name,$value,$custom=”",$class=”",$size=4,$minlength=4,$maxlength=4,$validate=true) {
if($validate==true) {
$this->validation .= “frmvalidator.addValidation(\”$name\”,\”maxlen=$maxlength\”);\n\r
frmvalidator.addValidation(\”$name\”,\”req\”);\n\r
frmvalidator.addValidation(\”$name\”,\”num\”);\n\r
frmvalidator.addValidation(\”$name\”,\”minlen=$minlength\”);\n\r”;
}
if($class != “”) {
$class = “class=\”$class\”";
}
return “\n\r”;
}
function checkbox($name,$value,$custom=”",$class=”",$checked = false) {
if($checked == true) {
$checked = “checked=\”checked\”";
} else {
$checked = “”;
}
return “”;
}
function ffile($name,$custom=”") {
return “”;
}
//insert into database
function DB_INSERT($table,$ignore_array=array(”,’ACTIONS’,'Submit’,'submit’)) {
$array_size=count($_GET);
$array_keys=array_keys($_GET);
$myinsert = new mysql();
$fields = array();
$values = array();
for($x=0; $xquery($sql);
return “Record Added”;
}
//insert into database
function DB_POST_INSERT($table,$ignore_array=array(”,’ACTIONS’,'Submit’,'submit’)) {
$array_size=count($_POST);
$array_keys=array_keys($_POST);
$myinsert = new mysql();
$fields = array();
$values = array();
for($x=0; $xquery($sql);
return “Record Added”;
}
function DB_UPDATE($TABLE,$TABLE_KEY,$TABLE_KEY_VALUE,$IGNORE_ARRAY=array(”,’ACTIONS’,'Submit’,'submit’)) {
$array_size=count($_POST);
$array_keys=array_keys($_POST);
$myupdate = New mysql();
if(isset($_POST['ACTIONS'])){
for($x=0; $xquery($sql);
return “Fields UPDATED”;
}
}
function DB_GET_UPDATE($TABLE,$TABLE_KEY,$TABLE_KEY_VALUE,$IGNORE_ARRAY=array(”,’ACTIONS’,'Submit’,'submit’)) {
$array_size=count($_GET);
$array_keys=array_keys($_GET);
$myupdate = New mysql();
if(isset($_GET['ACTIONS'])){
for($x=0; $xquery($sql);
return “Fields UPDATED”;
}
}
function DB_DELETE($TABLE,$TABLE_KEY,$TABLE_KEY_VALUE) {
$mydelete = New mysql();
$sql=”DELETE FROM “.$TABLE.” WHERE “.$TABLE_KEY.”= ‘”.$TABLE_KEY_VALUE.”‘ “;
$mydelete->query($sql);
return “Fields DELETE”;
}
function EMAIL_FROM($TO_EMAIL,$FROM_EMAIL,$SUBJECT,$IGNORE_ARRAY=array(”,’ACTIONS’,'Submit’,'submit’)) {
$array_size=count($_POST);
$array_keys=array_keys($_POST);
require(“../../class/class.phpmailer.php”);
if(isset($_POST['ACTIONS'])){
for($x=0; $x< $array_size; $x++) {
$key=array_search($array_keys[$x], $IGNORE_ARRAY);
if($key==NULL){
if($array_keys[$x]=="HEADER"){
$form_key.=$_POST[$array_keys[$x]]."”;
}
else
{
$form_key.=”“.$array_keys[$x].” : “.$_POST[$array_keys[$x]].”";
}
}
}
$mymail = new PHPMailer();
$mymail->IsMail();
$mymail->From = $FROM_EMAIL;
$mymail->FromName = $FROM_EMAIL;
$mymail->AddAddress($TO_EMAIL);
//$mymail->AddReplyTo($my_site->get_site_contact_form_email());
$mymail->WordWrap = 50;
$mymail->IsHTML(true);
$mymail->Subject = $SUBJECT;
$mymail->Body = $form_key;
if(!$mymail->Send())
{
$error.=EMAIL_ERROR;
$error.=’Mailer Error: ‘ . $mymail->ErrorInfo;
return $error;
}
else
{
return $form_key;
}
}
}
}
?>
http://gist.github.com is your friend, you should get to know him
seems to have been screwed up in the cut and past email me if you would like a copy
I think this idea just like any Helper function on Framewok, and it does helping
Can you shoot me an e-mail with your Form Class?
oops, my e-mail is eli007s@gmail.com
A lot of these comments are similar, and my thoughts are too. You can make a helper for this, and a helper for that, but in the end, you end up with a framework (unless your app is small). Why not use a framework like CodeIgniter or Kohana? Then, you don’t have to do anything except learn the framework, which is very easy.
It’s GOOD to learn programming outside of a packaged library of classes or ‘framework’.
i don’t feel comfortable relying too heavily on third-party libraries ever since the painful transition out of the ‘wordpress’ world. not a slight against CI or Kohana – both of which are awesome. but understanding the core concepts, and then realizing how simple they are to program yourself is a real eye opener to how much I have learned about programming. for me, i DO want to ‘get’ programming, and these kinds of tutorials are great for taking those first steps (even if just mentally) out of the boundaries of a framework. you can also abstract away the concept of relational tables, but i would never be able to grasp certain concepts without having an understanding of ‘data normalization’ and SQL. doesn’t mean i’m writing custom queries for every project, nor does it mean i don’t abstract as much as i can. but the progression from writing random spaghetti scripts embedded in crappy HTML into writing functions and then to OOP is a very satisfying feeling.
That’s useful for dynamic links. I am thinking to add it to my workflow. Form elements (checkboxes etc) would be useful too.
The biggest problem with helpers is the fact that it’s miss-used…
A helper should be used to “help” you do advanced coding in one or two lines, for example:
function mail_me($from_name, $from_email, $message) {
return mail(‘name@domain.tld’, ‘subject’, ‘message from ‘.$from_name.’ (‘.$from_email.’)’.”\n”.$message, ‘some-headers’);
}
or
function debug($val) {
print ”;
print_r($val);
print ”;
}
and not stuff like:
function e($s) {
echo $e;
}
Just my two cents…
This is a real eye-opener. I’m still fairly new to php so stuff like this really can speed up productivity! It’s great that everyone else comes up with their own alternatives/opinions in the comments but for the people this tut is really aimed at a well structured tutorial is always going to be more helpful.
Thanks.
Codeigniter anchor() copy…
Great tutorial. Thanks
I just don’t get it. Why do people need tutorials for this kind of stuff. That’s what coding is all about. Writing classes or functions to get a job done. I’m really confused by comments like “never thought about this”, “really usefull”. How did you guys code in the past???
I suggest to use some kind of HTML class. So you can nest several instances or use polymorphism for the rendering.
Some people don’t have a coding past, a lot of visitors are still beginners.
Yeah I know. But it’s sad to see, that people don’t learn the basics anymore in a proper way.
@Markus and that’s exactly the reason why people need tutorials like this one
Everyone learns in their own way.
Did you pop out into this world as an expert programmer? I know people who did, so I’m not being a dick, it’s a real question. My cousin picked up a Commodore 64 and just started programming these cool games, and all i could do was play them. I, most certainly, did not have the benefit of a natural capability. I’m coming from a marketing / sales background, and have really dedicated the last year or two to learning proper programming. when you don’t have to rely on the programming team to implement your ideas, it makes marketing so much more effective and fun (and you make more loot). I didn’t take any CS classes in school, I was more on the business side. I have found a lot of people out there like me, and the available information is great, but brutal for people like me until little ‘a ha’ moments that are probably painfully obvious and elementary to you, but just boosted me from level 4 to 6.
Thanks for the great resources!
Lucas
http://mindboxstudios.com
http://twitter.com/mindboxstudios
Jesus
function tag($tag, $content, $attr){
return ”. $content .”;
}
I find myself using pre tags and the print_r() function a lot when debugging.
I’m brand new to PHP OOP concepts, but I created a very basic method for this. The only thing I wish it could due is display the variable being passed into $varvar. As far as I know, PHP can’t do that…
When using this method, you will need a private static class variable that sets $devStatus to 0 for “off” or 1 for “on”.
public static function devDump($varvar) {
if (isset(self::$devStatus) && self::$devStatus==1) {
print “”;
print_r($varvar);
print “”;
}
}
In my code, I call it like this (assuming $helper is the instantiated object):
print ‘$extras: ‘;
$helper->devDump($extras);
If someone can improve this, by all means, please do!!
Of course, the print pre tags were slaughtered in my previous post.
Since you’re using a static function you don’t need an instance fo the class to call the function. So instead of
$helper = new HelperClass();
$helper->devDump($extra);
you can just call
HelperClass::devDump($extra)
These helpers are open to HTML injection. Would have been better to show people the safe and non-vulnerable way to write them.
The helpers should remember to correctly encode the data given to it into the HTML and not just string concat the raw values.
[)amien
Very good article. Thanks a lot.
very useful tutorials for beginners. For me, I am using my helper functions since I started programming.
Hey Michael, do you author programmers.biz ?? If not man i’d suggest you tell the author to take his cut & paste copy of this blog post …including images!! from his posts. or atleast comment you as its author its annoying, check this out!
http://programmers.biz/programming/increase-productivity-by-creating-php-helper-functions/
Outrageous. What an absolute dumb douchebag. I’ll try and send him an email, although it’s probably better coming from envato.
Ye, you have us nice ideas, but using a framework can save us much more time than creating ours. CodeIgniter helpers give us much flexibility and time, so I’m gonna keep using it until a full PHP+AJAX framework appears
Thanks anyway!
I’m very surprised no one’s ever thought about this… seriously.
Hey Michael
Thanks for such great and detailed Tutorial. Can i as you or other PHP Gurus one question. Which is good frame work . I mean there are many like .Smarty, phpCake, Codeigniter etc. Can you Php gurus out there suggest me which one should i use.
Well i am newbie in web development and want to learn it i know basic Php Stuff
Thanks
All three that you mention are great, and, as many have suggested in the comments, I have a liking for CodeIgniter. These kinds of helper tools are available in php frameworks, but I would seriously consider working out how to create them yourself first.
Reliance in open source code is good, because it saves time, but if it means you don’t understand the details, and you are using a framework as a shortcut to knowledge it can cause problems in the long run.
That’s why I wanted to write this series. I think it’s wise to learn how to do all these things from scratch first, so that your knowledge is more complete.
Google does not actually index the content of the title attribute on anchor elements, so it is not at all important for SEO. In most cases, the anchor text should describe the link adequately.
@jayphen – has Google said officially that it doesn’t take the title attribute into any consideration when indexing / ranking ? where did you read that?