Redirect page in php w3schools


Learn how to redirect to another webpage using JavaScript.


Redirect a Webpage

There are a couple of ways to redirect to another webpage with JavaScript. The most popular ones are location.href and location.replace:

Example

// Simulate a mouse click:
window.location.href = "http://www.w3schools.com";

// Simulate an HTTP redirect:
window.location.replace("http://www.w3schools.com");

Try it Yourself »

Note: The difference between href and replace, is that replace() removes the URL of the current document from the document history, meaning that it is not possible to use the "back" button to navigate back to the original document.



When you open a Web page in your browser, apart from the web page, you're also bringing back something called an HTTP HEADER. It is some additional information, such as a type of programme making the request, date requested, should it be displayed as an HTML document, how long the document is, and a lot more besides.

PHP headers can perform certain things, some of them are listed below:

  • Tell browser not to cache the pages.
  • Content-Type declaration
  • Page Redirection

Redirecting Browser

You can redirect your user to some other page.

<?php
  header("Location: http://www.example.com/");
?>

The following command will redirect the browser window to the given location as soon as the command is executed.

Please note that Location starts with capital L, some browsers might not redirect if small l is used.

Even though you redirected the user successfully, yet this is not the proper way to do it. The above command does not generate the 301 response which means the target page will lose a hit count and SEO ranking. To avoid that, you have to add an additional header.

<?php
  header("HTTP/1.1 301 Moved Permanently");
  header("Location: http://www.example.com/");
?>

Furthermore, you can add some redirection interval by using the following code:

<?php
  header("Refresh: 5; url=http://www.example.com"); //will redirect after 5 seconds
?>

Do not cache pages

You can prevent the browser to cache pages by using the following code:

<?php
  //Date in the past, tells the browser that the cache has expired
  header("Expires: Mon, 20 Feb 2005 20:12:03 GMT");
  
  /* The following tell the browser that the last modification is right not so it must load the page again */
  header("Last-Modified: ". gmdate("D, d M Y H:i:s"). "GMT");
  
  //HTTP/1.0
  header("Pragma: no-cache");
?>

The above code will let the browser load the page fresh from the server every time it is called. The reason is simple; we tell the browser that the content just expired and it was just last modified too. Furthermore, we also tell it Pragma: no-cache to make sure it gets a fresh server copy each time.

Content Types

Other than HTML, you can also generate different types of data, e.g., you can parse an image, zip, XML, JSON, etc. If you do that then, you need to tell to the browser that content type is something else.

<?php
  //Browser will deal page as PDF
  header ( "Content-type: application/pdf" );
  
  //myPDF.pdf will called
  header ( "Content-Disposition: attachment; filename=myPDF.pdf' " );
?>


Redirect page in php w3schools

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.

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:

<?php 
  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:

<?php 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 ?>

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);

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.

Here is an example:

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();
  }
}

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:

<!DOCTYPE html>
<html>
  <head>
    <title>window.location function</title>
  </head>
  <body>
    <p id="demo"></p>
    <script>
      document.getElementById("demo").innerHTML =
        "URL: " + window.location.href + "</br>";
      document.getElementById("demo").innerHTML =
        document.getElementById("demo").innerHTML +
        "Hostname: " + window.location.hostname + "</br>";
      document.getElementById("demo").innerHTML =
        document.getElementById("demo").innerHTML +
        "Protocol: " + window.location.protocol + "</br>";
    </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.

How do I redirect to another page in PHP w3schools?

Redirecting Browser php header("Location: http://www.example.com/"); ?> The following command will redirect the browser window to the given location as soon as the command is executed. Please note that Location starts with capital L, some browsers might not redirect if small l is used.

How do I redirect a HTML page to a PHP page?

Answer: Use the PHP header() Function You can simply use the PHP header() function to redirect a user to a different page. The PHP code in the following example will redirect the user from the page in which it is placed to the URL http://www.example.com/another-page.php . You can also specify relative URLs.

How do I redirect from one page to another?

How to Redirect to Another Page in HTML. To redirect one HTML page to another page, you need to add a <meta> tag inside the <head> section of the old HTML page. The <head> section of an HTML document contains metadata that is useful for the browser, but invisible to users viewing the page.

What is redirection PHP?

PHP. 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.