phpformscodeignitersanitizationcodeigniter-form-helper

CI - Sanitizing the form inputs from quotes


I was facing an issue where if I submit characters like single quotes ( ' ) or double quotes ( " ) and if I retain the values after submitting the form, (due to validation failure, for instance), I was getting form values like ' and "

I tried a lot of things like -

But nothing helped. Finally, I went to system\helpers\form_helper.php and changed function form_input at line 177 as follows -

Previous : $defaults = array('type' => 'text', 'name' => (( ! is_array($data)) ? $data : ''), 'value' => $value);

After : $defaults = array('type' => 'text', 'name' => (( ! is_array($data)) ? $data : ''), 'value' => html_entity_decode($value, ENT_QUOTES, 'UTF-8'));

This has solved my problem without any break so far.

All I want to know if this is the correct way to serve the purpose?


Solution

  • I am not super sure about the issue you were having but editing the system file to fix it is not a great idea. You should never change anything in the system folder, the proper way to make your change would be to extend the form helper by creating the file application/helpers/MY_form_helper.php (using your own prefix, defined in application/config/config.php) and inside the file override the function you want to change. It should look something like this...

    <?php
    defined('BASEPATH') OR exit('No direct script access allowed');
    
    if ( ! function_exists('form_input'))
    {
        /**
        * Text Input Field
        *
        * @param    mixed
        * @param    string
        * @param    string
        * @return   string
        */
        function form_input($data = '', $value = '', $extra = '')
        {
            $defaults = array(
                'type' => 'text',
                'name' => is_array($data) ? '' : $data,
                'value' => html_entity_decode($value, ENT_QUOTES, 'UTF-8')
            );
            return '<input '._parse_form_attributes($data, $defaults).$extra." />\n";
        }
    }
    
    /* End of file MY_form_helper.php */
    /* Location: ./application/helpers/MY_form_helper.php */