🛡️ CodeIgniter 4 Security Guide
Essential Security Practices for PHP 8.2
Security should never be an afterthought in web development. With CodeIgniter 4 and PHP 8.2, you have powerful tools to build secure applications from the ground up.
🔒 Input Validation & Sanitization
⚠️ Common Vulnerability
Never trust user input without proper validation and sanitization.
Validation Rules Implementation
<?php
namespace App\Controllers;
class UserController extends BaseController
{
protected $validation;
public function __construct()
{
$this->validation = \Config\Services::validation();
}
public function register()
{
$rules = [
'username' => [
'label' => 'Username',
'rules' => 'required|min_length[3]|max_length[20]|alpha_numeric',
'errors' => [
'required' => 'Username is required',
'alpha_numeric' => 'Username must contain only letters and numbers'
]
],
'email' => [
'label' => 'Email',
'rules' => 'required|valid_email|is_unique[users.email]'
],
'password' => [
'label' => 'Password',
'rules' => 'required|min_length[8]|regex_match[/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/]'
]
];
if (!$this->validate($rules)) {
return view('register', ['errors' => $this->validator->getErrors()]);
}
// Process validated data
$userData = [
'username' => $this->request->getPost('username'),
'email' => $this->request->getPost('email'),
'password' => password_hash($this->request->getPost('password'), PASSWORD_DEFAULT)
];
// Save to database
$userModel = new \App\Models\UserModel();
$userModel->insert($userData);
return redirect()->to('/login')->with('success', 'Registration successful');
}
}
🔐 CSRF Protection
Enable CSRF Globally
// app/Config/Security.php
public $csrfProtection = 'session';
public $tokenRandomize = true;
public $tokenName = 'csrf_token_name';
public $headerName = 'X-CSRF-TOKEN';
public $cookieName = 'csrf_cookie_name';
public $expires = 7200;
public $regenerate = true;
CSRF in Forms
<!-- In your view file -->
<form method="post" action="/user/update">
<?= csrf_field() ?>
<input type="text" name="username">
<input type="email" name="email">
<button type="submit">Update Profile</button>
</form>
💉 SQL Injection Prevention
✅ Best Practice: Always use Query Builder or prepared statements
// ✅ Safe: Using Query Builder
$users = $this->db->table('users')
->where('email', $email)
->where('status', 'active')
->get()
->getResultArray();
// ✅ Safe: Using Model with bindings
$user = $this->userModel->where('id', $userId)->first();
// ❌ Dangerous: String concatenation
$query = "SELECT * FROM users WHERE email = '" . $email . "'";
// ✅ Safe: Manual prepared statement
$query = $this->db->query(
"SELECT * FROM users WHERE email = ? AND status = ?",
[$email, 'active']
);
🌐 XSS Protection
Output Escaping
<!-- Always escape output in views -->
<h1><?= esc($title) ?></h1>
<p><?= esc($userContent, 'html') ?></p>
<!-- For attributes -->
<input type="text" value="<?= esc($value, 'attr') ?>">
<!-- For JavaScript -->
<script>
var userData = <?= esc($jsonData, 'js') ?>;
</script>
🔑 Authentication & Authorization
Secure Session Management
<?php
class AuthService
{
public function login(string $email, string $password): bool
{
$userModel = new UserModel();
$user = $userModel->where('email', $email)->first();
if (!$user || !password_verify($password, $user['password'])) {
return false;
}
// Regenerate session ID to prevent session fixation
session()->regenerate();
// Store minimal user info in session
session()->set([
'user_id' => $user['id'],
'username' => $user['username'],
'role' => $user['role'],
'logged_in' => true,
'last_activity' => time()
]);
// Update last login
$userModel->update($user['id'], ['last_login' => date('Y-m-d H:i:s')]);
return true;
}
public function logout(): void
{
session()->destroy();
session()->regenerate();
}
public function isLoggedIn(): bool
{
return session()->get('logged_in') === true;
}
}
🚀 Security Checklist
- ✅ Enable HTTPS in production
- ✅ Use environment variables for sensitive data
- ✅ Implement rate limiting
- ✅ Keep CodeIgniter and PHP updated
- ✅ Use secure headers (HSTS, CSP)
- ✅ Regular security audits
#Security
#CodeIgniter4
#PHP8.2
#WebSecurity
Remember: Security is an ongoing process, not a one-time setup. Stay updated with the latest security practices and regularly audit your applications.
Stay secure, code responsibly! 🛡️
0 Comments