How can PHP be used to escape special characters when passing variables through links to prevent security vulnerabilities?

When passing variables through links in PHP, it is crucial to escape special characters to prevent security vulnerabilities such as SQL injection or cross-site scripting attacks. This can be achieved by using the `urlencode()` function to encode the variables before appending them to the URL.

<?php
$variable = "Hello, world!"; // Variable to be passed through link
$escaped_variable = urlencode($variable); // Escape special characters
$link = "example.php?var=" . $escaped_variable; // Append escaped variable to URL
echo '<a href="' . $link . '">Click here</a>'; // Output link with escaped variable
?>