- How to Redirect a Web Page with PHP
- Using the header() Function
- Using a Helper Function
- JavaScript via PHP
- PHP Redirects – How to Create and Configure them
- PHP Redirect Basic Syntax
- PHP Redirect Example
- This my page2
- PHP Redirect with Absolute URL
- PHP Redirect with Time Delay
- Conclusion
- Recent Posts
- How to Redirect With PHP
- Learn PHP With a Free Online Course
- How Does Basic Redirection Work?
- How Redirection Works in PHP
- How to Use Header Function
- Why Should You Use the Die() or Exit() Function After the Header Redirection?
- The Famous Error: Headers Are Already Sent
- Conclusion
- The Best PHP Scripts on CodeCanyon
How to Redirect a Web Page with PHP
This short snippet will show you multiple ways of redirecting a web page with PHP.
So, you can achieve redirection in PHP by following the guidelines below.
Using the header() Function
This is an inbuilt PHP function that is used for sending a raw HTTP header towards the client.
The syntax of the header() function is as follows:
header( $header, $replace, $http_response_code )
Also, it is likely to apply this function for sending a new HTTP header, but one should send it to the browser prior to any text or HTML.
Let’s see how to redirect a web page using the header() function:
header('Location: //www.w3docs.com'); // or die(); exit(); ?>
As you can notice, exit() is used in the example above. It is applied to prevent the page from showing up the content remained (for instance, prohibited pages).
Also, you can use the header() function with ob_start() and ob_end_flush() , like this:
ob_start(); //this should be first line of your page header('Location: target-page.php'); ob_end_flush(); //this should be last line of your page
Using a Helper Function
Here, we will demonstrate how to use a helper function for redirecting a web page. Here is an example:
function Redirect($url, $permanent = false) < header('Location: ' . $url, true, $permanent ? 301 : 302); exit(); > Redirect('//www.w3docs.com/', false);
All HTTP status codes are listed at HTTP Status Messages
Note that this function doesn’t support 303 status code!
Let’s check out a more flexible example:
function redirect($url, $statusCode = 303) < header('Location: ' . $url, true, $statusCode); die(); >
In some circumstances, while running in CLI (redirection won’t take place) or when the webserver is running PHP as a (F) CGI, a previously set Statusheader should be set to redirect accurately.
function Redirect($url, $code = 302) < if (strncmp('cli', PHP_SAPI, 3) !== 0) < if (headers_sent() !== true) < if (strlen(session_id()) > 0) < // if using sessions session_regenerate_id(true); // avoids session fixation attacks session_write_close(); // avoids having sessions lock other requests > if (strncmp('cgi', PHP_SAPI, 3) === 0) < header(sprintf('Status: %03u', $code), true, $code); > header('Location: ' . $url, true, preg_match('~^30[1237]$~', $code) > 0 ? $code : 302); > exit(); > > ?>
JavaScript via PHP
Here, we will provide you with an alternative method of redirection implementing JavaScript via PHP. In JavaScript, there is a windows.location object that is implemented for getting the current URL and redirecting the browser towards a new webpage. This object encompasses essential information about a page (for example, href, a hostname, and so on).
This is how to redirect a web page using window.location:
html> html> head> title>window.location function title> head> body> p id="demo"> p> script> document.getElementById("demo").innerHTML = "URL: " + window.location.href + ""; document.getElementById("demo").innerHTML = document.getElementById("demo").innerHTML + "Hostname: " + window.location.hostname + ""; document.getElementById("demo").innerHTML = document.getElementById("demo").innerHTML + "Protocol: " + window.location.protocol + ""; script> body> html>
To conclude, let’s assume that in this short tutorial, we provided you with multiple methods to redirect a web page with PHP. Also, you can find information on how to redirect web pages with HTML, JavaScript, Apache and Node.js.
PHP Redirects – How to Create and Configure them
PHP redirect is a method used to redirect a user from one page to another page without clicking any hyperlinks.
This will be helpful in such circumstances when you want to redirect a certain page to a new location, change the URL structure of a site and redirect users to another website.
Redirection is very important and frequently used in Web Development phases.
There are several reasons to use PHP redirect, including, Merger of two websites, Change of business name, Redirect traffic to updated content and many more.
In this tutorial, we will learn how to redirect PHP page with the header() function.
PHP Redirect Basic Syntax
To use a redirect in PHP, we use a header() function. The header() function is an inbuilt function in PHP which is used to send a raw HTTP header to the client.
Basic syntax of header() function in PHP redirect is shown below:
header( header, replace, http_response_code )
Each parameter is described below:
- header:
This is used to hold the header string to send - replace:
Indicates the header should replace a previous similar header, or add a second header of the same type - http_response_code:
This is used to hold the HTTP response code
PHP Redirect Example
In this section, we will give you a quick example of how to create a redirect using PHP.
In this example, we will create a page1.php that contains code that issues a redirect and page2.php that contains just HTML.
Add the following contents:
Save and close the file. Then, create a page2.php:
Add the following contents:
This my page2
Save and close the file, when you are finished.
Next, you can test the URL redirection by visiting the page1.php at URL http://localhost/page1.php. You will be redirected to the page2.php as shown below:
You can also test the URL redirection with Curl command:
curl -I http://localhost/page1.php
You should see the following output:
HTTP/1.1 302 Moved Temporarily
Server: nginx/1.4.6 (Ubuntu)
Date: Wed, 11 Sep 2019 09:48:42 GMT
Content-Type: text/html
Connection: keep-alive
X-Powered-By: PHP/5.5.9-1ubuntu4.29
Location: page2.php
By default, search engine replies with the default response code 302 while Browser reply with the response code 30x.
If you want to redirect page1.php to another site https://www.webservertalk.com with response code 301 then edit the php1.php file with the following contents:
Add the following contents:
header(«Location: https://www.webservertalk.com»,TRUE,301);
exit;
?>
Save and close the file. Then, check PHP redirect again with the Curl command:
curl -I http://localhost/page1.php
You should see the following output:
HTTP/1.1 301 Moved Permanently
Server: nginx/1.4.6 (Ubuntu)
Date: Wed, 11 Sep 2019 10:21:58 GMT
Content-Type: text/html
Connection: keep-alive
X-Powered-By: PHP/5.5.9-1ubuntu4.29
Location: https://www.webservertalk.com
PHP Redirect with Absolute URL
In the above examples, The URL does not contain a hostname, this will work on modern browser. But, it is better to redirect to an absolute URL.
You can achieve this by editing the page1.php file as shown below:
Make the following chages:
header(‘Location: http://’ . $_SERVER[‘HTTP_HOST’] . ‘/page2.php’);
exit;
?>
Save and close the file when you are finished. Then, you can test it with your web browser or Curl command.
PHP Redirect with Time Delay
You can also redirect PHP page to another page with refresh function instead of Location.
For example, create a page1.php that redirect to page2.php after 10 seconds:
Add the following contents:
header( «refresh:10; url=/page2.php» );
echo «Redirecting in 10 secs.»;
exit;
?>
Save and close the file. Then, check the URL redirection by visiting the URL http://localhost/page1.php. You should see the following page:
Above page indicates that page1.php will redirects after 10 seconds.
Conclusion
In the above tutorial, we have learned how to redirect URL from one page to another with PHP header() function.
I hope you have now enough knowledge on how PHP redirection works. For more information, you can visit the PHP redirect documentation at PHP redirect.
Recent Posts
- Forcepoint Next-Gen Firewall Review & Alternatives
- 7 Best JMX Monitoring Tools
- Best PostgreSQL Backup Tools
- Best CSPM Tools
- Best Cloud Workload Security Platforms
- Best Automated Browser Testing Tools
- Event Log Forwarding Guide
- Best LogMeIn Alternatives
- Citrix ShareFile Alternatives
- SQL Server Security Basics
- Cloud Security Posture Management Guide
- Cloud Workload Security Guide
- The Best JBoss Monitoring Tools
- ITL Guide And Tools
- 10 Best Enterprise Password Management Solutions
How to Redirect With PHP
Sajal Soni Last updated May 21, 2020
Redirection allows you to redirect the client browser to a different URL. You can use it when you’re switching domains, changing how your site is structured, or switching to HTTPS.
In this article, I’ll show you how to redirect to another page with PHP. I’ll explain exactly how PHP redirects work and show you what happens behind the scenes.
Learn PHP With a Free Online Course
If you want to learn PHP, check out our free online course on PHP fundamentals!
How Does Basic Redirection Work?
Before we dive into the specifics of PHP redirection, let’s quickly understand how exactly HTTP redirection works. Take a look at the following diagram.
Let’s understand what’s going on in the above screenshot:
- The client browser requests a specific page from the server. In the above example, the client has requested the contents of the index.php file.
- The server receives the index.php file request and wants to inform the client that it’s no longer available or moved somewhere else, and it should look to a new file instead: new_index.php. The server sends the Location header with a new URL along with the 301 or 302 HTTP code. These are the HTTP codes for redirection.
- When a client browser encounters the 301 or 302 code, it knows that it has to initiate another request to a new URL to fetch the content. It initiates a request to fetch the new_index.php file in the above example.
- Finally, a server sends the contents of the new URL.
So that’s how a basic HTTP redirection works. In the next section, we’ll discuss how PHP redirection works.
How Redirection Works in PHP
In PHP, when you want to redirect a user from one page to another page, you need to use the header() function. The header function allows you to send a raw HTTP location header, which performs the actual redirection as we discussed in the previous section.
How to Use Header Function
Let’s go through the syntax of the header() function.
header( $header, $replace, $http_response_code )
- $header : This is the HTTP header string that you want to use. In our case, we’ll use the Location header for redirection.
- $replace : It’s an optional parameter which indicates whether the header should replace a previous similar header.
- $http_response_code : It allows you to send a specific response code.
Now, let’s have a look at the following example to understand how it all works together.
header("Location: https://www.yoursite.com/new_index.php");
When the above script is executed, it’ll redirect the client browser to http://www.yoursite.com/new_index.php. In the background, it sends a raw HTTP Location header along with the 302 status code. The 302 status code is used for temporary redirection, but if you want permanent redirection, you can pass the 301 code in the third argument, as shown in the following snippet.
header("Location: http://www.yoursite.com/new_index.php", TRUE, 301);
The 301 permanent redirect allows you to inform the search bots that the page is no longer available, and it can be replaced with a new page.
Why Should You Use the Die() or Exit() Function After the Header Redirection?
Users with sharp eyes would have noticed that I’ve used the exit() function in the above example. In fact, it’s mandatory that you use either the exit() or the die() function immediately after the header redirection to stop script execution and avoid any undesired results.
So it’s always recommended practice to use one of these functions after redirection.
The Famous Error: Headers Are Already Sent
If you’re an experienced PHP programmer, I’m sure you’ve come across this famous PHP error at some point in your day-to-day PHP development. For beginners, however, encountering this error is really annoying, since it’s really hard to debug and fix. In most cases, they don’t even have a clue that it’s caused by the header redirection.
The rule of thumb is that when you use the header() function in your script, you need to make sure that you don’t send any output before it. Otherwise, PHP will complain with the «headers are already sent» error. This can happen even if you’ve sent a single white space before using the header function.
Conclusion
In this post, we discussed one of the important features of PHP programming: redirection. First, we went through the basics of HTTP redirection, and then I demonstrated how it works in PHP.
The Best PHP Scripts on CodeCanyon
Explore thousands of the best and most useful PHP scripts ever created on CodeCanyon. With a low-cost one-time payment, you can purchase one of these high-quality WordPress themes and improve your website experience for you and your visitors.
Here are a few of the best-selling and up-and-coming PHP scripts available on CodeCanyon for 2020.