What are the best practices for encoding user input to ensure correct URL formatting in PHP and JavaScript?

When dealing with user input that will be used in URLs, it is important to properly encode the input to ensure correct URL formatting and prevent potential security vulnerabilities. In PHP, you can use the urlencode() function to encode user input before using it in URLs. In JavaScript, you can use the encodeURIComponent() function for the same purpose. PHP code snippet:

$user_input = "example user input";
$encoded_input = urlencode($user_input);
echo "Encoded input: " . $encoded_input;