In what situations should PHP_SELF be used and how can it be properly implemented to avoid security vulnerabilities?

Using PHP_SELF can lead to security vulnerabilities such as Cross-Site Scripting (XSS) attacks. To avoid these vulnerabilities, it is recommended to use htmlspecialchars() function to sanitize the input and prevent any malicious scripts from being executed.

<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post">
    <!-- form fields go here -->
</form>