Developer Blog

  • Blog
  • /
  • Escaping output and helper functions
By Dracony on 27 August 2013

Using PHP templating has a significant drawback of being unable to automatically escape your variables when they are being displayed. So if you had avariable like “Fairy

Tinkerbell” it might break your layout. Though PHPixie automatically strips tags on all user input thus closing most routes to using an XSS attack on your website it is still usefull to escape most of the string your output.

I struggled to find a nice solution for this for a while, because obviously it had to be something short but I also wanted to stick to OOP as much as possible. The solution was to add a \View\Helper class with its instance being passed to each view. Methods of that class may also be aliased to shorter variables. The first method is output () and its alias $_()that will escape and print out a string. For example:

1
2
3
4
5
6
7
8
9
// inside a view
<!-- Old way -->
<div><?php echo $fairy->name; ?></div>

<!-- Using a helper. Rather long-->
<div><?php $helper->output($fairy->name);></div>

<!-- Using a shortcut -->
<div><?php $_($fairy->name); ?></div>

To add your own methods to the helper just extend the \PHPixie\View\Helper class.

Helper shortcuts are nothing special really, they are just variables that are autoassigned into your view (yes, $_ is a valid PHP variable name ). If you add your own methods to the Helper class you can assign them any alises you like. E.g.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// /classes/App/View/Helper
namespace App\View;

class Helper extends \PHPixie\View\Helper{

    protected $aliases = array(
    '_' => 'output',
    '_r' => 'repeat'
    );
    public function repeat($str, $times) {
        for($i = 0;$i<$times; $i++)
            echo $str;
    }
}

Now you will be able to use the alias inside the view:

1
2
<!-- Will print <br/> 3 times -->
<?php $_r('<br/>',3) ?>

Hope you’ll like this new feature and enjoy the added security benefit of outputting filtered variables =]

comments powered by Disqus