GuardAPI Logo
GuardAPI

Fix XSS in API Responses in Phalcon

API-based XSS in Phalcon occurs when user-supplied data is reflected back into the response body without proper content-type enforcement or escaping. Even if the payload is wrapped in JSON, a missing or incorrect 'Content-Type' header (like 'text/html') can trick a browser into sniffing and executing malicious scripts. As a researcher, I see this often when developers use 'echo' instead of the Phalcon Response object.

The Vulnerable Pattern

public function searchAction() {
    $name = $this->request->getQuery('name');
    // VULNERABLE: Direct echo with manual string concatenation
    // If name is , it reflects directly.
    echo '{"status": "error", "message": "User ' . $name . ' not found"}';
}

The Secure Implementation

The fix is two-fold: 1. Content-Type Enforcement: By setting 'application/json', you instruct the browser to treat the body as data, not executable HTML. 2. Proper Serialization: The 'setJsonContent' method uses PHP's json_encode under the hood, which automatically escapes characters that could break out of a string context. Never manually concatenate JSON strings; always use the framework's response abstraction to ensure headers and encoding are handled correctly.

public function searchAction() {
    $name = $this->request->getQuery('name');
    // SECURE: Use Phalcon Response object, set Content-Type, and use setJsonContent
    return $this->response
        ->setContentType('application/json', 'UTF-8')
        ->setJsonContent([
            'status' => 'error',
            'message' => 'User ' . $name . ' not found'
        ]);
}
System Alert • ID: 4156
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.