What best practice should be followed when using the header() function in PHP for redirection?

When using the header() function in PHP for redirection, it is important to ensure that no output has been sent to the browser before calling the function. This is because the header() function sends an HTTP header to the browser, and if any content has already been sent, it will cause an error. To prevent this, you should call the header() function before any output is sent, including any whitespace or HTML tags.

<?php
// Correct way to redirect using header() function
header("Location: https://www.example.com");
exit;
?>