5

I am using CodeIgniter and on an edit form its pulling in data from the database. Sometimes this data contains apostrophes, ampersands etc..

How can i get CI to not parse this and change it to HTML version so end users can edit it.!

This is an image of the edit form, this text field has data pulled in from the database and populated into the input text field. The data does not contain any special chars as you can see in the second image below.

enter image description here

Here is a screenshot of how the data looks in the table, note i am only pulling from the far right column. Not the 4th column: enter image description here

As you can tell the data isnt being stored as html converted, yet CI is still converting it.

Here is a snippet of the above text field:

<?php    
/**
 * Form Field attribute settings
 * @author Mike DeVita
 */
$companyname = array(
    'name'  => 'companyname',
    'placeholder' => 'Enter Your Companies Name',
    'id'    => 'companyname',
    'value' => set_value('', $points['pointFields']['companyname']->uf_fieldvalue),
    'maxlength' => 80,
    'size'  => 30
);
            <div class="_100">
                <p><?php echo form_label('Company Name', $companyname['id']); ?><?php echo form_input($companyname); ?></p>
                <?php echo form_error($companyname['id']); ?>
            </div>

Here is a snippet of the insert to database:

function addUserFieldHtml($compiledHtml){
    foreach ($compiledHtml as $cHK => $cHV){
        $data = array (
            'pointid' => $cHV['pointId'],
            'timestamp' => time(),
            'html' => $cHV['html'],
            'fieldid' => $cHV['fieldId'],
            'fieldvalue' => $cHV['fieldValue']
        );
        $this->db->insert('userfields', $data);

    }
}#end addUserFieldHtml() function

Thanks

3
  • I'm not quite sure how you're generating form elements, but I would guess you have a prep_for_form filter running? In any case, your best option might be to use html_entity_decode (php.net/manual/en/function.html-entity-decode.php) or a similar decoding function on the data after it's been retrieved from the database but before the editor is being rendered.
    – rjz
    Apr 15, 2012 at 3:39
  • Can we see your actual code? How are you outputting the form inputs?
    – Mog
    Apr 15, 2012 at 4:26
  • @rjz I think you mean htmlspecialchars_decode() ?
    – Philip
    Apr 15, 2012 at 6:00

6 Answers 6

3

The issue is here:

$companyname = array(
    'value' => set_value('', $points['pointFields']['companyname']->uf_fieldvalue),
);

set_value() converts some characters to entities, and should only be used in raw HTML - not passed to any of the form helper functions, like so:

<input name="email" value="<?php echo set_value('email'); ?>">

This will call the form_prep() function which escapes the input string, something like this:

<input name="username" value="<?php echo form_prep($row->username); ?>">

So just change your config for value to this:

$companyname = array(
    'value' => $points['pointFields']['companyname']->uf_fieldvalue,
);

...and when used with form_input() or any of the other form helper functions for displaying an input, the value will be escaped properly for you. For example:

echo form_input('myinput', '</div>"someJunkInput"<?php'); // Good to go
2
  • Thanks a million, i shoulda read the doc more thoroughly.. Ill try to remember to offer you a bounty reward on this.
    – NDBoost
    Apr 15, 2012 at 5:50
  • 1
    Thanks but don't worry about it, just spread the knowledge :)
    – Mog
    Apr 15, 2012 at 5:51
1

CodeIgniter handles magic quote automatically in post variable and ensures that post variable does not carry any extra slash.

Hence you must ensure that you pass the data through addslashes() before running the query using simple_query() or query(). This ensures that your query is ok and not subject to sql injection. Do not use htmlspecialchars() or htmlentities() before database insert. That is a wrong practice.

However if you use $this->db->insert(); or $this->db->update() you do not need to apply addslashes() on post data.

Now before rendering data, use htmlspecialchars() in view. This will give you protection against XSS attack.

<input value="<?php=htmlspecialchars($val)?>" type="button">
2
  • Your solution in regards to rendering data did not work.. added: 'value' => set_value('', htmlspecialchars( $points['pointFields']['companyname']->uf_fieldvalue) ), does not work.
    – NDBoost
    Apr 15, 2012 at 5:43
  • Can you echo this $points['pointFields']['companyname']->uf_fieldvalue directly in the view directly and check whether &amp; is there or not using view source.
    – Ashim Saha
    Apr 15, 2012 at 5:59
1

I use it like this:

$tavall = html_entity_decode($task->description, ENT_QUOTES, 'UTF-8');

then in form input (in my case textarea):

form_textarea(array(
    'name'          => 'task_description',
    'id'            => 'task_description',
    'value'         => set_value('task_description', $tavall), // 
    'rows'          => 10,
    'cols'          => 40,
))

same for text inputs will work.

1

From CodeIgnitor 3.0 documentation:

set_value($field[, $default = ''[, $html_escape = TRUE]])
Parameters: 
$field (string) – Field name
$default (string) – Default value
$html_escape (bool) – Whether to turn off HTML escaping of the value
Returns:    
Field value

Return type:    
string

Permits you to set the value of an input form or textarea. You must supply the field name via the first parameter of the function. The second (optional) parameter allows you to set a default value for the form. The third (optional) parameter allows you to turn off HTML escaping of the value, in case you need to use this function in combination with i.e. form_input() and avoid double-escaping.

By setting the third parameter to false you can prevent conversion of quotes like below:

  ....
 'value' => set_value('control_name',$control[0]['control_name'],false),
  ....
0

CodeIgniter automatically passes the $_POST array through htmlspecialchars() when you use set_value(). If you take a look at the set_value() function in the form_helper.php, you will see that the desired value is passed through form_prep() which executes a htmlspecialchars() on the desired field.

In order to avoid this, you need to extend the form_helper adding a third optional parameter that skips the form_prep() execution. Just copy the following code into a MY_form_helper.php and copy it to application/helpers/

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * Form Value
 *
 * Grabs a value from the POST array for the specified field so you can
 * re-populate an input field or textarea.  If Form Validation
 * is active it retrieves the info from the validation class
 * NEW: Added a third parameter prep to skip htmlspecialchars escaping
 *
 * @access  public
 * @param   string
 * @return  mixed
 */
if ( ! function_exists('set_value'))
{
    function set_value($field = '', $default = '', $prep = true)
    {
        if (FALSE === ($OBJ =& _get_validation_object()))
        {
            if ( ! isset($_POST[$field]))
            {
                return $default;
            }

            return $prep ? form_prep($_POST[$field], $field) : $_POST[$field];
        }

        return $prep ? form_prep($OBJ->set_value($field, $default), $field) : $OBJ->set_value($field, $default);
    }
}


/* End of file MY_form_helper.php */
/* Location: ./application/helpers/MY_form_helper.php */
0

Use this code:

$test = 'hello "B"';
set_value('test', $test, false)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.