I woke up today thinking about how to handle strings when inserting to MySQL. What if the string I am trying to save into the database contains HTML characters? Let’s say you are using FCKEditor, how would you “generally” handle strings to be inserted into your database? Because when I think of it, I don’t have a quick answer. I have to test it around until satisfied with the output.
If I am too strict of what to save — then I would have problems outputting the HTML into the browser. Tables would be messed up and form elements would not work.
So, how do you filter different kinds of data to be inserted into MySQL using Zend Framework? Kinds of data as in:
- Strings with HTML characters (mostly from a CMS form where it needs to render the HTML again)
- usernames (no special characters)
- passwords
- what about encoding?
ZF has a filter plugin to escape html.
kimbou, can you show a short example?
To filter incoming data Zend Framework has special kind of classes: Zend_Filter_*. You can find them in the Zend/Filter directory. There are a lot of filters for different situation.
Below I show you a simple example of using them.
Zend_Loader::loadClass(‘Zend_Filter_StripTags’);
// create filter object
$oF = new Zend_Filter_StripTags();
// get filtered data from $_POST
$sSomeText = $oF->filter($this->_request->getPost(‘some_text’));
In this example we filtered $_POST['some_text'] data with StripTags filter.
Also with new Zend Framework 1.5 release there are ability to add filters directly to the Form Elements when you use Zend_Form class for automatically filtering incoming data. It’s very usefull method.
Thanks Roman! I have just started Zend_Form a few weeks ago. I started with Akrabat’s Zend_Form Tutorial ( http://akrabat.com/2008/02/21/simple-zend_form-example/ ).
I love Zend_Form! Especially the “populate”-form and the validators and filters makes my life easier
i love you