How can PHP_SELF be properly used in form actions to avoid errors related to server variables?

When using PHP_SELF in form actions, it can lead to security vulnerabilities such as cross-site scripting attacks. To avoid these errors, it is recommended to use htmlspecialchars() function to sanitize the input and prevent malicious code injection.

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