GuardAPI Logo
GuardAPI

Fix XSS in API Responses in CodeIgniter

XSS in API responses occurs when an application reflects unsanitized user input in a response body without setting the correct 'Content-Type' header. In CodeIgniter, failing to use the Response object allows browsers to potentially sniff the content as HTML, leading to script execution. As a researcher, I see this most often when devs use 'echo' instead of the framework's response handlers.

The Vulnerable Pattern

public function profile() {
    $username = $this->request->getGet('user');
    // VULNERABLE: Direct echo without explicit Content-Type header.
    // If a victim visits /profile?user=, some browsers may render it.
    echo json_encode(['status' => 'success', 'message' => 'Welcome ' . $username]);
}

The Secure Implementation

The fix relies on two layers: Header Enforcement and Output Encoding. Using '$this->response->setJSON()' forces the 'Content-Type: application/json' header, which instructs modern browsers not to parse the response as HTML. Additionally, using 'esc()' or ensuring 'json_encode' is used prevents raw injection. To harden this further, always implement a 'Content-Security-Policy' (CSP) and set the 'X-Content-Type-Options: nosniff' header in your CodeIgniter Filters to prevent MIME-sniffing attacks.

public function profile() {
    $username = $this->request->getGet('user');
    // SECURE: Use CI4 Response object. setJSON() automatically sets 
    // 'Content-Type: application/json' and handles encoding.
    return $this->response
                ->setStatusCode(200)
                ->setJSON([
                    'status' => 'success', 
                    'message' => 'Welcome ' . esc($username)
                ]);
}
System Alert • ID: 5364
Target: API Responses API
Potential Vulnerability

Your API Responses API might be exposed to XSS

74% of API Responses apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.

RUN FREE SECURITY DIAGNOSTIC
GuardLabs Engine: ONLINE

Free Tier • No Credit Card • Instant Report

Verified by Ghost Labs Security Team

This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.