== How to fix it in Core PHP === Code examples The following code is vulnerable to cross-site scripting because it returns an HTML response that contains user input. User input embedded in HTML code should be HTML-encoded to prevent the injection of additional code. PHP provides the built-in function `htmlspecialchars` to do this. ==== Noncompliant code example [source,php,diff-id=1,diff-type=noncompliant] ---- echo '

' . $input . '

'; ---- ==== Compliant solution [source,php,diff-id=1,diff-type=compliant] ---- echo '

' . htmlspecialchars($input) . '

'; ---- If you do not intend to send HTML code to clients, the vulnerability can be fixed by specifying the type of data returned in the response with the content-type header. For example, setting the content-type to `text/plain` using the built-in `header` function allows to safely reflect user input since browsers will not try to parse and execute the response. ==== Noncompliant code example [source,php,diff-id=2,diff-type=noncompliant] ---- echo $input; ---- ==== Compliant solution [source,php,diff-id=2,diff-type=compliant] ---- header('Content-Type: text/plain'); echo $input; ---- === How does this work? include::../../common/fix/data_encoding.adoc[] === Pitfalls include::../../common/pitfalls/content-types.adoc[] ==== Single quoted variables in attributes By default, `htmlspecialchars` does not encode single quotes, so if `++$input++` is untrusted, JavaScript code can be injected. Make sure to set the option `ENT_QUOTES` to encode single quotes. ===== Noncompliant code example [source,php,diff-id=3,diff-type=noncompliant] ---- echo ""; ---- ===== Compliant solution [source,php,diff-id=3,diff-type=compliant] ---- echo ""; ---- ==== Headers and output If the HTTP body is sent before `header` is called, no headers will be sent to the client. To fix this issue, send the headers before any output. ===== Noncompliant code example [source,php,diff-id=4,diff-type=noncompliant] ---- echo 'No more headers at this point'; header('Content-Type: text/plain'); echo $input; ---- ===== Compliant solution [source,php,diff-id=4,diff-type=compliant] ---- header('Content-Type: text/plain'); echo $input; ---- === Going the extra mile include::../../common/extra-mile/csp.adoc[]