CodeIgniter Basic Tutorial
Performance & Utilities
CodeIgniter Advanced
Security is one of the most important aspects of any web application.
CodeIgniter provides built-in security features to help protect your application from common threats such as:
This tutorial explains how to use CodeIgniter’s security features step by step.
CodeIgniter’s Query Builder automatically escapes values, preventing SQL injection.
✅ Example (Safe):
$this->db->where('id', $this->input->get('id')); $query = $this->db->get('users');
⚠️ Avoid writing raw queries with user input unless you escape them properly:
// Unsafe ❌ $query = $this->db->query("SELECT * FROM users WHERE id=" . $_GET['id']);
XSS attacks happen when hackers inject malicious JavaScript into your site.
CodeIgniter provides an xss_clean()
function to filter inputs.
✅ Example:
$data = $this->input->post('username', TRUE); // Second parameter TRUE applies XSS Filtering
Or use Security Class:
$this->security->xss_clean($data);
CSRF attacks trick users into submitting unwanted actions.
CodeIgniter provides CSRF protection using a hidden token.
application/config/config.php
$config['csrf_protection'] = TRUE;
<form method="post" action="/submit"> <?php echo form_open('form/submit'); ?> <input type="text" name="name"> <input type="submit" value="Submit"> <?php echo form_close(); ?> </form>
CodeIgniter will automatically add a CSRF hidden token in the form and validate it.
Never store plain text passwords ❌.
Use password_hash()
and password_verify()
.
✅ Example:
// Storing password $hash = password_hash($this->input->post('password'), PASSWORD_BCRYPT); // Verifying password if (password_verify($this->input->post('password'), $hash)) { echo "Password Matched!"; }
When uploading files, always restrict file types and sizes.
✅ Example:
$config['upload_path'] = './uploads/'; $config['allowed_types'] = 'jpg|png|gif'; $config['max_size'] = 2048; // 2 MB $this->load->library('upload', $config); if (!$this->upload->do_upload('userfile')) { echo $this->upload->display_errors(); } else { $data = $this->upload->data(); echo "File uploaded successfully!"; }
To secure sessions:
✅ Example:
$this->session->sess_regenerate(TRUE);
CodeIgniter has helper functions:
html_escape($string)
→ Prevents XSS by escaping HTML.$this->input->get_post('name', TRUE)
→ Fetches input with XSS filtering.