Home How to make a redirect in PHP?
Reply: 23

How to make a redirect in PHP?

Sam Published in 2009-04-20 14:13:22Z

Is it possible to redirect a user to a different page through the use of PHP?

Say the user goes to www.example.com/page.php and I want to redirect them to www.example.com/index.php, how would I do so without the use of a meta refresh? Possible?

This could even protect my pages from unauthorized users.

vartec Reply to 2009-04-21 07:52:52Z

Use header() function to send HTTP Location header:

header('Location: '.$newURL);

Contrary to some think, die() has nothing to do with redirection. Use it only if you want to redirect instead of normal execution.


header('Location: static.html');
$fh = fopen('/tmp/track.txt','a');
fwrite($fh, $_SERVER['REMOTE_ADDR'].' '.date('c')."\n");

Result or 3 executions:

bart@hal9k:~> cat /tmp/track.txt 2009-04-21T09:50:02+02:00 2009-04-21T09:50:05+02:00 2009-04-21T09:50:08+02:00

Resuming — obligatory die()/exit() is some urban legend, that has nothing to do with actual PHP. Has nothing to do with client "respecting" Location: header. Sending header does not stop PHP execution, regardless of client used.

Zack Marrapese
Zack Marrapese Reply to 2009-04-20 19:47:17Z

you can update the header in php: header

Daniel A. White
Daniel A. White Reply to 2009-04-20 14:14:41Z

header( 'Location: http://www.yoursite.com/new_page.html' );

Alix Axel
Alix Axel Reply to 2009-04-28 03:14:38Z
function Redirect($url, $permanent = false)
    if (headers_sent() === false)
        header('Location: ' . $url, true, ($permanent === true) ? 301 : 302);


Redirect('http://www.google.com/', false);

Don't forget to die()/exit()!

Community Reply to 2017-05-23 11:47:36Z

Output JavaScript from PHP using echo, which will do the job.

echo '<script type="text/javascript">
           window.location = "http://www.google.com/"

You can't really do it in PHP unless you buffer the page output and then later check for redirect condition. That might be too much of a hassle. Remember that headers are the first thing that is sent from the page. Most of the redirect is usually required later in the page. For that you have to buffer all the output of the page and check for redirect condition later. At that point you can either redirect page user header() or simply echo the buffered output.

For more about buffering (advantages)

What is output buffering?

nickf Reply to 2009-04-20 14:33:34Z

Most of these answers are forgetting a very important step!

header("Location: myOtherPage.php");

Leaving that vital second line out might see you end up on The Daily WTF. The problem is that browsers do not have to respect the headers which your page return, so with headers being ignored, the rest of the page will be executed without a redirect.

Henrik Paul
Henrik Paul Reply to 2009-04-20 20:25:12Z

In the eve of the semantic web, correctness is something to consider. Unfortunately, PHP's "Location"-header still uses the HTTP 302-redirect code, which, strictly, isn't the best one for redirection. The one it should use instead, is the 303 one.

W3C is kind enough to mention that the 303-header is incompatible with "many pre-HTTP/1.1 user agents," which would amount to no browser in current use. So, the 302 is a relic, which shouldn't be used.

...or you could just ignore it, as everyone else...

Alix Axel
Alix Axel Reply to 2011-04-28 21:31:36Z

I've already answered this question, but I'll do it again since in the meanwhile I've learnt that there are special cases if you're running in CLI (redirects cannot happen and thus shouldn't exit()) or if your webserver is running PHP as a (F)CGI (it needs a previously set Status header to properly redirect).

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


I've also handled the issue of supporting the different HTTP redirection codes (301, 302, 303 and 307), as it was addressed in the comments of my previous answer, here are the descriptions:

  • 301 - Moved Permanently
  • 302 - Found
  • 303 - See Other
  • 307 - Temporary Redirect (HTTP/1.1)
Luke Reply to 2014-01-15 04:21:54Z

Many of these answers are correct, but they assume you have an absolute URL, which may not be the case. If you want to use a relative URL and generate the rest, then you can do something like this...

$url = 'http://' . $_SERVER['HTTP_HOST'];            // Get the server
$url .= rtrim(dirname($_SERVER['PHP_SELF']), '/\\'); // Get the current directory
$url .= '/your-relative/path-goes/here/';            // <-- Your relative path
header('Location: ' . $url, true, 302);              // Use either 301 or 302
joan16v Reply to 2015-01-12 11:03:32Z
header("Location: /index.php");
Vikram Pote
Vikram Pote Reply to 2015-03-12 09:42:18Z

you can use some java script methods like below



 3)document.location.href = 'http://www.example.com/index.php';  

jake Reply to 2016-06-14 13:47:00Z
<?php header('Location: another-php-file.php'); exit(); ?>

or if you have already opened php tags, use this:

header('Location: another-php-file.php'); exit();

You can also redirect to external pages, eg:

header('Location: https://www.google.com'); exit();

Make sure you include exit() or include die()

Asuquo12 Reply to 2016-12-02 08:19:47Z

You can use session variables to control access to pages and authorize valid users as well.



if ( !isset( $_SESSION["valid_user"]) )

      { header("location:../index");

// Page goes here


Shawn Reply to 2016-11-15 19:51:24Z

You can attempt to use the php header function to do the redirect. You will want to set the output buffer so your browser doesn't throw a redirect warning to the screen.

header("Location: ".$website);
Bhaskar Pramanik
Bhaskar Pramanik Reply to 2017-01-28 14:48:31Z

Probably too late to answer this one. Nevertheless, here are my thoughts:

IMHO, the best way to re-direct an incoming request would be by using location headers, which goes

header("Location: /index.php");

Once this statement is executed, and output sent out, the browser will begin re-directing the user. However, ensure that there hasn't been any output (any echo / var_dump) before sending headers, else it will lead to errors.

Although this is a quick and dirty way to achieve what was originally asked, yet it would eventually turn out to be an SEO disaster, as this kind of re-direct is always interpreted as a 301 / 302 re-direct, hence search engines will always see your index page as a re-directed page, and not something of a landing page / main page. Hence it will affect the SEO settings of the website.

sabuz Reply to 2017-04-09 09:38:07Z

The best way to Redirect with PHP is the following code...

 header("Location: /index.php");

Make sure no code will work after

header("Location: /index.php");

All the codes must be executed before the above line.


Case 1:

echo "I am a web developer";
header("Location: /index.php");

It will redirect properly to the location (index.php).

Case 2:

return $something;
header("Location: /index.php");

The above code will not redirect to the location(index.php).

Hopefully, It is clear.

Juned Ansari
Juned Ansari Reply to 2017-10-31 12:53:08Z

1. Using header function with exit()

     header('Location: target-page.php');

but if you use header function then some times you will get "warning like header already send" to resolve that do not echo or print before sending headers or you can simply use die() or exit() after header function.


2. Without header

    echo "<script>location.href='target-page.php';</script>";

here you will not face any problem

3. Using header function with ob_start() and ob_end_flush()

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
Bhargav Chudasama
Bhargav Chudasama Reply to 2017-06-08 09:48:28Z

Yes it's possible to use PHP, we will redirect to another page, try this one:

header("location:./");//redirect to index file
header("location:index.php");//redirect to index file
Obaidul Haque
Obaidul Haque Reply to 2017-08-18 06:46:30Z
header('Location: redirectpage.php');
header('Location: redirectpage.php');exit();
echo "<script>location.href='redirectpage.php';</script>";

This is regular and normal PHP redirect but you can make a redirecting a page with few second wait below code:

header('refresh:5;url=redirectpage.php '); //Note: here 5 means 5 seconds wait for redirect.
jabko87 Reply to 2017-10-13 10:56:05Z

If you're running on Apache you can also use .htaccess for redirect.

Redirect 301 / http://new-site.com/
Joshua Charles Pickwell
Joshua Charles Pickwell Reply to 2017-11-20 19:10:01Z
$url = "targetpage"
Function redirect$url(){
   If (headers_sent()) == false{
      Echo '<script>window.location.href="' . $url . '";</script>';
CasperSL Reply to 2017-11-28 01:11:32Z

Yes, you can use header() function,

header("Location: http://www.yourwebsite.com/user.php"); /* Redirect browser */

And also best practice is to call exit() function right after header() function to avoid below code execution.

According to the documentation, header() must be called before any actual output is sent.

Kavita Sharma
Kavita Sharma Reply to 2018-01-04 09:57:51Z

We can do in two way

  1. when user come on https://bskud.com/PINCODE/BIHAR/index.php then redirect to https://bskud.com/PINCODE/BIHAR.php

by below php code

<?php header("Location: https://bskud.com/PINCODE/BIHAR.php"); exit; ?>

Save Above code in https://bskud.com/PINCODE/BIHAR/index.php

2.When any condition true then redirect to other page

<?php  $myVar = "bskud";   if ($myVar == "bskud") { ?>  <script> window.location.href="https://bskud.com";  </script> <?php  } else {  echo "<b>Check Website Name Again</b>"; } ?>


You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.433607 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO