What are common pitfalls when redirecting URLs in PHP and how can they be avoided?

Common pitfalls when redirecting URLs in PHP include not using the correct header function, not exiting the script after the redirect, and not validating the URL before redirecting. To avoid these pitfalls, always use the header function with the "Location" parameter, immediately exit the script after the redirect, and validate the URL to prevent any malicious redirections.

// Redirect to a specific URL
$newURL = "https://www.example.com";
if (filter_var($newURL, FILTER_VALIDATE_URL)) {
    header("Location: " . $newURL);
    exit();
} else {
    // Handle invalid URL
    echo "Invalid URL";
}