What are the best practices for implementing 301 redirects in PHP to avoid potential pitfalls?

When implementing 301 redirects in PHP, it is important to ensure that the redirects are set up correctly to avoid potential pitfalls such as infinite loops or incorrect redirections. One best practice is to use the header() function in PHP to send the 301 redirect header along with the new location URL.

// Redirect to a new location with a 301 status code
header("HTTP/1.1 301 Moved Permanently");
header("Location: https://www.newlocation.com");
exit();