0
0
PHPprogramming~5 mins

How XSS attacks exploit unescaped output in PHP

Choose your learning style9 modes available
Introduction

XSS attacks happen when bad code sneaks into web pages because the website shows user input without cleaning it first. This can let attackers run harmful scripts on your site.

When displaying user comments on a blog without cleaning the text
When showing user names or messages that come from forms directly on a page
When building chat apps that show messages from many users
When creating pages that include user input in HTML without safety checks
Syntax
PHP
<?php
// Unsafe output example
echo $_GET['name'];

// Safe output example
echo htmlspecialchars($_GET['name'], ENT_QUOTES, 'UTF-8');
?>

Use htmlspecialchars() to convert special characters to safe HTML entities.

Always escape output before showing user input on a web page.

Examples
This prints user input directly, which is unsafe and can allow XSS.
PHP
<?php
echo $_GET['comment'];
?>
This safely shows user input by escaping special characters.
PHP
<?php
echo htmlspecialchars($_GET['comment'], ENT_QUOTES, 'UTF-8');
?>
Sample Program

This program shows how printing user input directly can run scripts, but using htmlspecialchars stops that by turning special characters into safe text.

PHP
<?php
// Simulate user input from URL parameter
$user_input = "<script>alert('XSS');</script>";

// Unsafe output (vulnerable to XSS)
echo "Unsafe output: " . $user_input . "\n";

// Safe output using htmlspecialchars
$safe_output = htmlspecialchars($user_input, ENT_QUOTES, 'UTF-8');
echo "Safe output: " . $safe_output . "\n";
?>
OutputSuccess
Important Notes

Never trust user input; always escape it before showing on pages.

Using htmlspecialchars is a simple and effective way to prevent many XSS attacks.

Remember to use the right character encoding like UTF-8 for safety.

Summary

XSS attacks happen when user input is shown without cleaning.

Use htmlspecialchars to escape special characters before output.

Always treat user input as unsafe until properly escaped.