Injecting unsanitized data into responses can lead to several security vulnerabilities, including Cross-Site Scripting (XSS) attacks. XSS attacks occur when a malicious script is injected into a trusted website, which can compromise the data integrity or steal sensitive information.
To comply with this rule, always sanitize or validate data before including it in a response. PHP provides several built-in functions such as filter_var(), htmlspecialchars(), and strip_tags() that can be used for sanitizing data.
Non-Compliant Code Examples
<?phpclassUserControllerextendsController{publicfunctiontest0($data){returnresponse('Data is '.$data,200)->header('Content-Type','text/html');}publicfunctiontest1($data){returnresponse("Data is {$data}")->withHeaders(['Content-Type'=>"text/html",]);}}Route::get('/endpoint/{data}',function($data){returnresponse("Data is {$data}")->cookie($cookie)->withHeaders(['Content-Type'=>'text/html',]);});
Compliant Code Examples
<?phpclassUserControllerextendsController{publicfunctiontest0($data){$content=sanitize($data);returnresponse('Data is '.$content,200)->header('Content-Type','text/html');}publicfunctiontest1($data){$content=validate($data);returnresponse("Data is {$content}")->withHeaders(['Content-Type'=>"text/html",]);}}Route::get('/endpoint/{data}',function($data){$var=sanitize($data);returnresponse("Data is {$var}")->cookie($cookie)->withHeaders(['Content-Type'=>'text/html',]);});
Seamless integrations. Try Datadog Code Analysis
Datadog Code Analysis
Try this rule and analyze your code with Datadog Code Analysis
How to use this rule
1
2
rulesets:- php-security # Rules to enforce PHP security.
Create a static-analysis.datadog.yml with the content above at the root of your repository
Use our free IDE Plugins or add Code Analysis scans to your CI pipelines