What are the best practices for encoding and decoding URLs in PHP when dealing with special characters?

When dealing with special characters in URLs in PHP, it is important to properly encode and decode them to ensure they are handled correctly. The best practice for encoding URLs is to use the urlencode() function, which converts special characters into their percent-encoded form. When decoding URLs, the urldecode() function should be used to revert percent-encoded characters back to their original form.

// Encoding URL with special characters
$url = "https://example.com/?name=" . urlencode("John Doe");
echo $url; // Output: https://example.com/?name=John+Doe

// Decoding URL with special characters
$decodedName = urldecode($_GET['name']);
echo $decodedName; // Output: John Doe