How to Use Header() Function in PHP?

Friends, today we are going to tell you about the header() function. Function in PHP is used to reduce the duplication of code and the clarity of the code is improved by the use of the function. The function also reduces complex problems into simple pieces. Function is a piece of code which takes input as parameter and returns a value after processing.
If you want to redirect one page to another page in PHP, then you can redirect using header() function. When a user visits the page of a website (opening the page), then after visiting, he gets redirected to another website page. We can use the PHP header() function to redirect from one page to another. Like a user login, after login, a separate page is opened, we can do that also with the help of header() function.
Let us understand from syntax –

syntax

header(string,replace,http_response_code)

string – header string to send (required,URL,page)
replace – Allows multiple headers of the same type (optional)
HTTP response code.- . This is an optional parameter. This forces the HTTP response code to be a specified value.
The header() function prevents sending more than one header at a time. If the haeder has already been sent, you get a fetch error like “Headers already sent”.

Examples of PHP header() function

Example

<?php
header("location:page_name.php");
?>

In the example above, we can use any page name. To redirect one page to another, we have to give the name of the page to which we want to redirect.

Redirecting using website URL via header() function

Using the header() function, we can also redirect from one website URL to another website URL. The header() function is used on the page from where we have to redirect to another page or URL.

Example

<?php
header("location:https://example.com/");
?>

Redirecting page URL to another page URL using header() function

If you are working on the same website, then you can redirect from one page URL to another page URL by using header() function.

Example

<?php
header("location:https://example.com/page_name.php");
?>

redirecting time period using header() function

By using PHP header() function, we can do redirection after some time. In this example, we set a few seconds, which takes some time for redirection. After the timeout, it gets redirected to another page. Whatever number of seconds you define, it takes the same number of seconds for redirection, after the second is over, it gets redirected to another page.

Example

<?php
header("refresh:5; url=https://example.com");
echo "Redirecting.....";
?>

It redirects to another page or URL after five seconds.

Note:- In this way you can use PHP header() function.