In this article, we are going to discuss how to add 301 redirects in PHP. Sometimes we come across scenarios like a few web pages redirecting from one page to another page without clicking/doing anything. This can be done by developers if they want users to use their updated version of their webpage rather than the older version. PHP provides an easy and flexible way to redirect from one page to another page by specifying the new PHP file in the header method in an old PHP file. So using the header method we can add 301 redirects in PHP.
Header Function: Header function is an inbuilt function in PHP that sends a raw HTTP header to the client. This header function must be called before any output is sent because they manipulate the information sent to the client. Let’s look into the syntax of the header function:
Syntax:
header(header, replace, http_response_code)
Parameters
- header- It is the string to send. It is a required parameter in header function.
- replace- Indicates the whether previous headers are replaced with new headers. Default value is True if not specified. It’s an optional parameter.
- http_response_code- Forces the http_response_code to a specified value. It’s also an optional parameter.
Returns None.
Let’s look into the steps to add 301 directs in PHP
Steps:
- The older source code file should be of the type PHP.
- Create a new source code file of type PHP to which it redirects.
- Add redirect code by specifying the new PHP file name in the header method in the older source code file.
Add the below mentioned source code in the old PHP file to add redirection.
<?php
header(“Location: https://www.domain.com/newFileName.php”, true, 301);
?>
<?php
header(“HTTP/1.1 301 Moved Permanently”);
header(“Location: https://www.domain.com/newFileName.php”);
header(“Connection: close”);
?>
Example: Here we will be having two source code files one with an older version of the code and another source code file that has a newer version code to which it redirects when the user runs the old source code file. Below is the redirected newFile.php source code file.
PHP
<?php echo "New Version" ?> |
The below source code oldFile.php had the code that redirects to the newFile.php
PHP
<?php header( "HTTP/1.1 301 Moved Permanently" ); header( "Connection: close" ); ?> |
Output
This will change the location of the header, i.e. redirects to specified newFile.php and executes the code in it. New Version
By using the oldFile.php source code file, Users will be redirected to domain.com/newFile.php and HTTP Status code 301 Moved Permanently is returned.
Note: If the header(“HTTP/1/1 301”) is not used then the HTTP status code is set to 302.