Signup/Sign In

How to make a redirect in PHP?

Answer: Using header() function

The header() function is an in-built PHP function. This function allows us to send the raw HTTP header. The header() function is called before any actual output is sent to the user. The HTTP header consists of the necessary information of the object which is sent in the message body.

The main function of the header() function is to redirect the user from the current page to another webpage/URL.

Syntax

The syntax of the header() function is given below:

header( $header, $replace, $http_response_code )
  • $header - The header parameter hold the HTTP header string.
  • $replace - This parameter indicates whether the headers should replace previous same header.
  • $http_response_code - This parameter holds the HTTP response code.

Example: Page Redirect in Php

In the given example, we have used the header() function to redirect the user from the current webpage to the another webpage. We have specified the URL of the webpage within the header() function which redirects the user to the home page of the "Studytonight".

<!DOCTYPE html>
<html>
<head>
	<title>header() function</title>
</head>
<body>
	<?php
	header("Location: https://www.studytonight.com/");
	exit();
	?>
</body>
</html>

Output

php1

In the above example, the header function sends the location of the header along with the 302 status code. The 302 status code is used for the temporary redirection, and for permanent redirection, we have to pass the 301 code in the third argument.

Example 2: Page Redirect in Php

Here, we call the header() method with other supportive arguments such as boolean value and status code.

<!DOCTYPE html>
<html>
<head>
	<title>header() function</title>
</head>
<body>
	<?php
	header("Location: https://www.studytonight.com/", true, 301);
	exit();
	?>
</body>
</html>

Output:

php2

Conclusion

In this lesson, we have learned how to make a redirect in PHP. So, redirection in PHP can be done using the header() function. The header() function enables us to send the raw HTTP location header, which performs actual redirection.



About the author:
I am the founder of Studytonight. I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development.