Jess McKenzie
Jess McKenzie

Reputation: 8385

Codeigniter Escaping Data

I am using the following code to allow me to add data to my db but it seems the $this->db->escape();is not working as I can add html tags and they will run in the view :(

Code:

$this->form_validation->set_rules('aPartyLocation','A Party Location', 'required|trim|prep_for_form|max_length[35]|xss_clean');
        $this->form_validation->set_rules('aPartyPhone','A Party Phone', 'required|trim|numeric|max_length[35]|xss_clean');

        if($this->form_validation->run() === TRUE)
            {
                $userData = array(
                    'location' => $this->input->post('aPartyLocation', TRUE),
                    'phone' => $this->input->post('aPartyPhone', TRUE));

                $this->db->escape($userData);
                $this->party_model->addAParty($userData);

Update:

Controller:

$userData = array(
    'id' => $id,
    'location' => html_escape($this->input->post('aPartyLocation', TRUE)),
    'phone' => html_escape($this->input->post('aPartyPhone', TRUE))
    );  

Model:

function addAParty($userData = NULL)
{
    $this->db->insert('aParty',$userData);
    return TRUE;
}

Upvotes: 1

Views: 6357

Answers (1)

Ayush
Ayush

Reputation: 42450

I would recommend you use CodeIgniter's Active Record class. This automatically escapes data for you.

For example, an insert statement would look like:

$this->db->insert('yourTable',array(
                 'location' => $this->input->post('aPartyLocation',TRUE),
                 'phone' => $this->input->post('aPartyPhone')
           ));

The second argument, is an array where the keys correspond to the columns in your database.


Edit

I believe Active Record only sanitizes data for SQL injection attacks. Passing the second parameter to $this->input->post() as TRUE protects your from XSS attacks. However, neither of those escape HTML tags. For that, you can use the htmlspecialchars function.

 $this->db->insert('yourTable',array(
                     'location' => htmlspecialchars($this->input->post('aPartyLocation',TRUE)),
                     'phone' => htmlspecialchars($this->input->post('aPartyPhone'))
                ));

$location = $this->input->post('aPartyLocation',TRUE);
$phone = $this->input->post('aPartyPhone');

 $this->db->insert('yourTable',array(
                     'location' => htmlspecialchars($location),
                     'phone' => htmlspecialchars($phone)
                ));

Upvotes: 3

Related Questions