In what situations should header() function be used in PHP, and how can conflicts with output be avoided?
The header() function in PHP should be used to send raw HTTP headers to the client. It is commonly used for tasks such as redirecting a user to a different page, setting cookies, or specifying the content type of the response. To avoid conflicts with output, the header() function must be called before any actual output is sent to the browser, including HTML tags, whitespace, or any other content.
<?php
// Call header() before any output is sent
header('Location: https://www.example.com');
exit;
?>
Related Questions
- What potential pitfalls should be considered when using regular expressions to filter HTML tags in PHP?
- What is the best way to sort a two-dimensional array in PHP based on the values in the second dimension?
- Are there any best practices for constructing and executing SQL queries in PHP to avoid syntax errors or compatibility issues with ODBC drivers?