XSS attack still works despite htmlspecialchars() doing its work



PHP Snippet 1:

<p><?php echo $user_entered_variable; ?></p>

PHP Snippet 2:

<p><?php echo htmlspecialchars($user_entered_variable); ?></p>

PHP Snippet 3:

<img title='<?php echo htmlspecialchars($user_entered_variable);?>'/>

PHP Snippet 4:

    <img title='<?php echo htmlspecialchars($user_entered_variable,ENT_QUOTES);?>'/>

PHP Snippet 5:

    <iframe src="<?php echo htmlspecialchars($user_entered_variable); ?>"></iframe>
    <img src="<?php echo htmlspecialchars($user_entered_variable); ?>">
    <a href="<?php echo htmlspecialchars($user_entered_variable); ?>">Link</a>

    <script>function openLink(link){window.open(link);}</script>
    <button onclick="openLink('<?php echo htmlspecialchars($user_entered_variable); ?>')">JavaScript Window XSS</button>

PHP Snippet 6:

 <?php

 $user_entered_variable = htmlspecialchars($user_entered_variable);
 $isValidURL = filter_var($user_entered_variable, FILTER_VALIDATE_URL) !== false;
 if(!$isValidURL)
    $user_entered_variable = 'invalid://invalid';
?>
    <iframe src="<?php echo $user_entered_variable; ?>"></iframe>
    <img src="<?php echo $user_entered_variable; ?>">
    <a href="<?php echo $user_entered_variable; ?>">Link</a>

    <script>function openLink(link){window.open(link);}</script>
    <button onclick="openLink('<?php echo $user_entered_variable; ?>')">JavaScript Window XSS</button>

PHP Snippet 7:

<script>
  var inputNumber = <?php echo $user_entered_variable; ?>
</script>

PHP Snippet 8:

<script>
  var inputNumber = <?php echo intval($user_entered_variable); ?>
</script>