What potential pitfalls should be considered when parsing URLs in PHP?

When parsing URLs in PHP, it is important to consider potential pitfalls such as user input validation, handling special characters, and ensuring proper encoding to prevent security vulnerabilities and unexpected behavior. One way to address these issues is by using PHP's built-in functions like filter_var() with the FILTER_VALIDATE_URL filter to validate URLs and urlencode() to properly encode URL components.

$url = "https://www.example.com/page.php?param=value";

// Validate URL
if (filter_var($url, FILTER_VALIDATE_URL)) {
    // Parse URL components
    $parsed_url = parse_url($url);
    
    // Encode URL components
    $encoded_query = urlencode($parsed_url['query']);
    
    // Output the encoded query string
    echo $encoded_query;
} else {
    echo "Invalid URL";
}