Reputation: 121
I'm developing an ecommerce site in CodeIgniter 3.1.11 and Active Records does not escape the single quote automatically. But in the documentation it is mentioned that Active records will automatically escapes the input.
$ar = array(
'name'=>"Jon'", //see the extra single quote here after the name Jon
);
$this->db->insert('test',$ar);
this code will add single quote in database and if i fetch this data and display this in HTML then any one can execute inline js there Eg. Jon' onmouseover='alert(1)
this input will execute inline js on the page.
<input type='text' name='username' value='Jon' onmouseover='alert(1)'
See here the onmouseover is added as the extra attribute.
$ar = array(
'name'=>$this->db->escape_str("Jon'"), //see the extra single quote here after the name Jon
);
$this->db->insert('test',$ar);
i have tried the escape_str function manually but this is adding backward slash before the single quote Jon\'
so inline js will not execute but its an ecommerce site it might be possible that there may be genuine single quotes are also there eg. Men's Clothes , Women's Clothes but if i use escape_str then it will be displayed as Mens\'s Clothes ,Women\'s Clothes
what to do in this situation? Any Suggestions?
Upvotes: 1
Views: 396
Reputation: 8007
use CI's function escape_str() to manually escape strings and when getting the data back the php function html_entity_decode():
echo html_entity_decode('joe\', Mens\'s Clothes, Women\'s Clothes');
which outputs
joe', Mens's Clothes, Women's Clothes
or better change your input field to:
<input type="text" name="username" value="" onmouseover="alert(1)">
then the automatic escaping from CI insert() will serve you, as inserting joe'
into value results in
<input type="text" name="username" value="joe'" onmouseover="alert(1)">
edit: hence you commented there are many files to change, you can also use this approach with htmlentities():
this php function transforms a single quote into '
and hence doesn't interfere with other single quotes in your code. The output by the browser is '
$ar = array(
'name'=>htmlentities("Jon'", ENT_QUOTES)
);
$this->db->insert('test',$ar);
note the use of the flag ENT_QUOTES
: which will convert both double and single quotes.
now in your html you'll get this code when getting the value from the database:
<input type='text' name='username' value='Jon'' onmouseover='alert(1)'>
which is not interfering anymore with your other single quotes (just run the code snippet)
Upvotes: 1