GuardAPI Logo
GuardAPI

Fix XSS in API Responses in Yii

XSS in APIs occurs when a backend reflects unsanitized user input in a response without enforcing a non-executable Content-Type. In Yii, failing to explicitly set the response format allows the browser to default to 'text/html' or perform MIME-sniffing, leading to script execution in the context of the domain. Hackers exploit this by sending payloads in query parameters or JSON bodies that the API echoes back.

The Vulnerable Pattern

public function actionSearch($query) {
    // VULNERABLE: Defaulting to HTML response and echoing raw input
    return 'Results for: ' . $query;
}

The Secure Implementation

The fix involves two layers of defense. First, explicitly setting 'Yii::$app->response->format' to 'FORMAT_JSON' forces the 'Content-Type: application/json' header. This tells the browser to treat the body as data, not as an executable document, effectively neutralizing reflected XSS. Second, returning an array instead of a string leverages Yii's JSON formatter, which automatically handles character encoding and ensures the payload is properly escaped within the JSON string. For legacy endpoints that must return HTML, use '\yii\helpers\Html::encode()' to sanitize the output.

public function actionSearch($query) {
    // SECURE: Force JSON response format and return structured data
    \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
    return [
        'message' => 'Results for search',
        'query' => $query
    ];
}
System Alert • ID: 4142
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.