How can one ensure that the URL variable is properly concatenated and formatted in header(Location: URL) in PHP?

When using the header(Location: URL) function in PHP to redirect to a specific URL, it is important to ensure that the URL variable is properly concatenated and formatted to avoid any errors or unexpected behavior. One way to ensure this is by using the urlencode() function to encode the URL parameter before concatenating it in the header function.

// Properly concatenate and format the URL variable in header(Location: URL)
$url = "https://example.com/page.php?id=1";
$encoded_url = urlencode($url);
header("Location: " . $encoded_url);
exit();