What are potential pitfalls or errors that can occur when using variables in links in PHP?

One potential pitfall when using variables in links in PHP is not properly sanitizing the input, which can lead to security vulnerabilities like SQL injection or cross-site scripting attacks. To avoid this, always validate and sanitize user input before using it in links.

// Example of sanitizing user input before using it in a link
$userInput = $_GET['input']; // Assuming user input is coming from a form field

// Sanitize the input using htmlentities to prevent XSS attacks
$sanitizedInput = htmlentities($userInput);

// Use the sanitized input in the link
echo "<a href='page.php?data=$sanitizedInput'>Link</a>";