How can urlencode be used effectively in PHP to ensure proper handling of URLs and prevent errors or security vulnerabilities?

When working with URLs in PHP, it is important to properly encode them using urlencode to ensure that special characters are handled correctly and to prevent errors or security vulnerabilities, such as injection attacks. By using urlencode, you can safely encode URLs before sending them as parameters in requests or storing them in databases.

$url = "https://www.example.com/page?param1=" . urlencode($param1) . "&param2=" . urlencode($param2);
echo $url;