Skip to content
PHP Logo

How can PHP handle header errors when using the header function for redirection?

When using the header function for redirection in PHP, it is important to handle any potential errors that may occur. One way to do this is by checking if headers have already been sent before using the header function. This can be done using the headers_sent function. If headers have already been sent, you can either output an error message or use alternative methods for redirection, such as using JavaScript or meta tags.

php
if (!headers_sent()) {
    header('Location: http://www.example.com');
    exit();
} else {
    echo "Error: Headers already sent";
    // Alternatively, use JavaScript or meta tags for redirection
}