This page is not yet available in Spanish. We are working on its translation.
If you have any questions or feedback about our current translation project, feel free to reach out to us!

Metadata

ID: php-security/html-xss

Language: PHP

Severity: Error

Category: Security

CWE: 79

Description

Cross-Site Scripting (XSS) attacks are a common type of security vulnerability in web applications. XSS attacks occur when an attacker can inject malicious scripts into web pages viewed by other users. These scripts can steal sensitive information, such as login credentials or personal data.

In PHP, this rule can be violated when user input is directly embedded into HTML without proper sanitization. This creates an opportunity for attackers to inject harmful scripts. For instance, if a user enters <script>alert('XSS')</script> as input, and this input is directly embedded into HTML, every user visiting the page will see an alert popup saying ‘XSS’.

Always sanitize user input before embedding it into HTML. This can be achieved by using the built-in PHP function htmlspecialchars(). This function converts special characters to their HTML entities, thereby preventing any embedded scripts from executing. For example, instead of writing echo '<h1>' . $input . '</h1>';, you should write echo '<h1>' . htmlspecialchars($input) . '</h1>';. This ensures that any user input is treated as plain text and not executable code.

Non-Compliant Code Examples

<?php
$input = $_GET["input"];
echo '<h1>' . $input . '</h1>';

Compliant Code Examples

<?php
$input = $_GET["input"];
echo '<h1>' . htmlspecialchars($input) . '</h1>';
<?php
header('Content-Type: text/plain');
$input = $_GET["input"];
echo $input;
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Analysis

PREVIEWING: antoine.dussault/service-representation-ga-docs-us1