What are some best practices for handling user input in PHP to prevent formatting errors in URLs?

When handling user input in PHP to prevent formatting errors in URLs, it is important to sanitize and validate the input to ensure it conforms to the expected format. One common approach is to use PHP's filter_var function with the FILTER_SANITIZE_URL filter to remove any potentially harmful characters or formatting. Additionally, encoding the user input using urlencode can help ensure that special characters are properly formatted in the URL.

// Sanitize and validate user input for URL
$userInput = $_GET['input'] ?? ''; // Get user input from query parameter
$cleanInput = filter_var($userInput, FILTER_SANITIZE_URL); // Sanitize input
$encodedInput = urlencode($cleanInput); // Encode input for URL

// Use the sanitized and encoded input in your URL
$url = "https://example.com/page?input=$encodedInput";
echo "<a href='$url'>Link</a>";