How can htmlspecialchars be appropriately used in PHP to handle URLs?

When handling URLs in PHP, it is important to properly sanitize the input to prevent cross-site scripting attacks. One way to do this is by using the htmlspecialchars function to encode special characters in the URL. This ensures that any user input included in the URL is properly escaped and does not pose a security risk.

$url = "https://www.example.com/?name=" . htmlspecialchars($_GET['name']);
echo "<a href='$url'>Click here</a>";