How can PHP_SELF be effectively used to retrieve the current URL in a PHP script, and what are common mistakes to avoid?

To retrieve the current URL in a PHP script, you can use the $_SERVER['PHP_SELF'] variable. This variable contains the filename of the currently executing script, making it a convenient way to get the current URL. However, it's important to be aware of security risks such as cross-site scripting (XSS) attacks when using PHP_SELF, so it's recommended to sanitize and validate the input before using it in your code.

$current_url = htmlspecialchars($_SERVER['PHP_SELF']);
echo "Current URL: $current_url";