By Sam


2009-04-20 14:13:22 8 Comments

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? Is it possible?

This could even protect my pages from unauthorized users.

30 comments

@Javed Khan 2019-05-29 06:34:42

There are two ways to redirection

Using PHP

<?php 

header("Location: http://example.com/page.php");
die();
?>

Using Jquery

<script>

     $(document).ready(function(){
    location.href = 'http://example.com/page.php';
     });

</script>

@Javed Khan 2019-05-29 06:35:44

Using Jquery $(document).ready(function(){ location.href ='www.example.com' });

@Kashif 2019-04-11 04:59:01

you can use this code redirect from one page to another

header("Location: index.php");

or if you try to redirect using JavaScript in php then use script tag for redirecting

echo "<script>window.open('your path where you redirect ','_self')</script>";

@user8031209 2019-03-29 12:29:01

using this code for better redirect:

$ref="http://www.example.com';
echo '<script>window.location = "'.$ref.'";</script>';  
exit;

@Luis H Cabrejo 2019-07-12 02:43:15

Work out great on my case. You are missing a " on your code for it to work with a copy and paste, otherwise is great ... Should read $ref="...whatever....";

@user8031209 2019-03-21 00:51:18

for redirect use this code

header("Location: http://www.example.com/blog");

@Asuquo12 2016-09-09 10:48:33

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

<?php
    session_start();

    if (!isset( $_SESSION["valid_user"]))
    {
        header("location:../");
        exit();
    }

    // Page goes here
?>

http://php.net/manual/en/reserved.variables.session.php.

Recently, I got cyber attacks and decided, I needed to know the users trying to access the Admin Panel or reserved part of the web Application.

So, I added a log access for the IP address and user sessions in a text file, because I don't want to bother my database.

@Bhargav Chudasama 2017-06-08 06:34:37

Yes, it's possible to use PHP. We will redirect to another page.

Try following code:

<?php
    header("location:./"); // Redirect to index file
    header("location:index.php"); // Redirect to index file
    header("location:example.php");
?>

@Star 2018-02-13 09:26:52

To redirect the visitor to another page (particularly useful in a conditional loop), simply use the following code:

<?php
    header('Location: mypage.php');
?>

In this case, mypage.php is the address of the page to which you would like to redirect the visitors. This address can be absolute and may also include the parameters in this format: mypage.php?param1=val1&m2=val2)

Relative/Absolute Path

When dealing with relative or absolute paths, it is ideal to choose an absolute path from the root of the server (DOCUMENT_ROOT). Use the following format:

<?php
    header('Location: /directory/mypage.php');
?>

If ever the target page is on another server, you include the full URL:

<?php
    header('Location: http://www.ccm.net/forum/');
?>

HTTP Headers

According to HTTP protocol, HTTP headers must be sent before any type of content. This means that no characters should ever be sent before the header — not even an empty space!

Temporary/Permanent Redirections

By default, the type of redirection presented above is a temporary one. This means that search engines, such as Google Search, will not take the redirection into account when indexing.

If you would like to notify search engines that a page has been permanently moved to another location, use the following code:

<?
    header('Status: 301 Moved Permanently', false, 301);
    header('Location: new_address');
?>

For example, this page has the following code:

<?
    header('Status: 301 Moved Permanently', false, 301);
    header('Location: /pc/imprimante.php3');
    exit();
?>

When you click on the link above, you are automatically redirected to this page. Moreover, it is a permanent redirection (Status: 301 Moved Permanently). So, if you type the first URL into Google, you will automatically be redirected to the second, redirected link.

Interpretation of PHP Code

The PHP code located after the header() will be interpreted by the server, even if the visitor moves to the address specified in the redirection. In most cases, this means that you need a method to follow the header() function of the exit() function in order to decrease the load of the server:

<?
    header('Status: 301 Moved Permanently', false, 301);
    header('Location: address');
    exit();
?>

@Peter Mortensen 2019-02-18 09:25:56

Why (near the end of the second paragraph)? Do you mean &para instead (so the whole reads mypage.php?param1=val1&param2=val2))? (The HTML entity para) is "¶" - perhaps some external program did a conversion?).

@Juned Ansari 2017-04-13 12:44:35

1. Using header function with exit()

<?php 
     header('Location: target-page.php');
     exit();
?>

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

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

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

@DoctorDroid Haiti 2019-03-27 15:38:45

Work like a charm. I use <?php echo "<script>location.href='google.fr/';</script>"; ?> To test it , and it did what i wanted

@Shaan Ansari 2018-08-03 13:26:57

1. Using header, a built-in PHP function

a) Simple redirect without parameters

<?php
   header('Location: index.php');
?>

b) Redirect with GET parameters

<?php
      $id = 2;
      header("Location: index.php?id=$id&msg=succesfully redirect");
  ?>

2. Redirect with JavaScript in PHP

a) Simple redirect without parameters

<?php
     echo "<script>location.href='index.php';</script>";
 ?>

b) Redirect with GET parameters

<?php
     $id = 2;
     echo "<script>location.href='index.php?id=$id&msg=succesfully redirect';</script>";
   ?>

@Pyr James 2018-01-28 22:17:07

There are multiple ways of doing this, but if you’d prefer php, I’d recommend the use of the header() function.

Basically

$your_target_url = “www.example.com/index.php”;
header(“Location : $your_target_url”);
exit();

If you want to kick it up a notch, it’s best to use it in functions. That way, you are able to add authentications and other checking elemnts in it.

Let’s try with by checking the user’s level.

So, suppose you have stored the user’s authority level in a session called u_auth.

In the function.php

<?php
    function authRedirect($get_auth_level,
                          $required_level,
                          $if_fail_link = “www.example.com/index.php”){
        if ($get_auth_level != $required_level){
            header(location : $if_fail_link);
            return false;
            exit();
        }
        else{
            return true;
        }
     }

     . . .

You’ll then call the function for every page that you want to authenticate.

Like in page.php or any other page.

<?php

    // page.php

    require “function.php”

    // Redirects to www.example.com/index.php if the
    // user isn’t authentication level 5
    authRedirect($_SESSION[‘u_auth’], 5);

    // Redirects to www.example.com/index.php if the
    // user isn’t authentication level 4
    authRedirect($_SESSION[‘u_auth’], 4);

    // Redirects to www.someotherplace.com/somepage.php if the
    // user isn’t authentication level 2
    authRedirect($_SESSION[‘u_auth’], 2, “www.someotherplace.com/somepage.php”);

    . . .

References;

@Kavita Sharma 2018-01-04 07:30:17

We can do it in two ways:

  1. When the user comes on https://bskud.com/PINCODE/BIHAR/index.php then redirect to https://bskud.com/PINCODE/BIHAR.php

    By the below PHP code

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

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

  2. When any condition is true then redirect to another page:

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

@Scriptman 2018-01-18 09:51:41

What is this? Please don't use links to your own website. And the second example uses javascript redirect, and not the PHP header() function.

@CasperSL 2017-11-28 01:04:54

Yes, you can use the header() function,

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

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

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

@Joshua Charles Pickwell 2017-11-20 19:10:01

Use:

<?php
    $url = "targetpage"
    function redirect$url(){
        if (headers_sent()) == false{
            echo '<script>window.location.href="' . $url . '";</script>';
        }
    }
?>

@www139 2017-11-20 19:38:15

Could you explain the function of your code? Your answer was flagged because of its length and content.

@Obaidul Haque 2017-08-18 06:46:30

Use:

<?php
    header('Location: redirectpage.php');
    header('Location: redirectpage.php');
    exit();
    echo "<script>location.href='redirectpage.php';</script>";
?>

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

<?php
    header('refresh:5;url=redirectpage.php '); // Note: here 5 means 5 seconds wait for redirect.
?>

@sabuz 2017-04-09 08:37:42

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 code must be executed before the above line.

Suppose,

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

@Patrick Hund 2017-04-09 09:00:24

There is already an answer that has 1085 that contains the info you provide, plus much more.

@Bhaskar Pramanik 2017-01-28 14:48:31

Here are my thoughts:

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

<?php
    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, it would eventually turn out to be an SEO disaster, as this kind of redirect is always interpreted as a 301 / 302 redirect, 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.

@EKanadily 2017-02-17 07:05:25

exit() should be used immediately after the header()

@Bhaskar Pramanik 2017-02-20 04:23:22

@docesam .. agreed .. exit() should be immediately called after header() call. However I feel, if there is no more output to browser after this header() statement, exit() may not be necessary - Just my opinion

@EKanadily 2017-02-21 02:47:36

yes but you have to explain that because someone could copy your line of code to his script and that can potentially cause long times of circling around himself figuring out what went wrong.

@aswzen 2018-03-22 03:40:43

@BhaskarPramanik imagine you have to lock a door quickly, but then you have to pull/push/smash them again to make sure if it already locked or not..

@Doruk Ayar 2016-11-15 10:15:19

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.

ob_start();
header("Location: " . $website);
ob_end_flush();

@EKanadily 2017-02-17 07:07:13

exit() should be used immediately after the header() . also out buffering has been automatically on by default for some time now.

@jake 2016-05-16 13:12:55

Use:

<?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, e.g.:

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

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

@Vikram Pote 2015-03-12 09:42:18

You can use some JavaScript methods like below

  1. self.location="http://www.example.com/index.php";

  2. window.location.href="http://www.example.com/index.php";

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

  4. window.location.replace("http://www.example.com/index.php");

@chharvey 2015-08-07 19:35:24

Javascript runs on the client which may or may not be what you're looking for.

@Alix Axel 2011-04-28 21:31:36

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

        exit();
    }
}

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)

@vartec 2009-04-20 14:14:11

Use the header() function to send an HTTP Location header:

header('Location: '.$newURL);

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

File example.php:

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

Result of three executions:

[email protected]:~> cat /tmp/track.txt
127.0.0.1 2009-04-21T09:50:02+02:00
127.0.0.1 2009-04-21T09:50:05+02:00
127.0.0.1 2009-04-21T09:50:08+02:00

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

@clawr 2009-04-21 00:59:38

die() or exit() is for clients who don't respect the "Location: ..." header

@Alix Axel 2013-06-05 17:24:12

@clawr: No, exit() is to prevent the page from showing up the remaining content (think restricted pages). vartec is right, it has nothing to do with the HTTP Location header and you don't need to exit. I chose to include it in my answer because, for someone who doesn't know how to do a simple redirect, one might as well play safe rather than not implement a simple yet crucial step just so he is able to take advantage of advanced process control.

@FrancescoMM 2017-03-21 17:45:53

But browsers that respect the header will leave the page and close the connection while your script is still executing. This is totally bad. PHP will go on with the script for some time (that's why your code executes) but may abort it randomly in the middle of execution, leaving stuff broken. Calling ignore_user_abort() will prevent this, but sincerely I it's not worth it. Just go on with your HTML writing stuff (though probably useless) but don't do stuff that writes on disk or database after a header('Location:'); Write to disk before the redirect if possible. [Also: url should be absolute.]

@BugWhisperer 2019-08-07 00:53:02

is there any way to redirect before the browser detects the HTTP protocol? the reason i need to redirect is because i cannot get enough SSL certificates for all of my domains. i'd use .htaccess to redirect, but i need a way to somehow pass on which domain redirected to the final domain?

@markus 2009-04-20 14:19:24

Summary of existing answers plus my own two cents:

1. Basic answer

You can use the header() function to send a new HTTP header, but this must be sent to the browser before any HTML or text (so before the <!DOCTYPE ...> declaration, for example).

header('Location: '.$newURL);

2. Important details

die() or exit()

header("Location: http://example.com/myOtherPage.php");
die();

Why you should use die() or exit(): The Daily WTF

Absolute or relative URL

Since June 2014 both absolute and relative URLs can be used. See RFC 7231 which had replaced the old RFC 2616, where only absolute URLs were allowed.

Status Codes

PHP's "Location"-header still uses the HTTP 302-redirect code, but this is not the one you should use. You should consider either 301 (permanent redirect) or 303 (other).

Note: W3C mentions that the 303-header is incompatible with "many pre-HTTP/1.1 user agents. Currently used browsers are all HTTP/1.1 user agents. This is not true for many other user agents like spiders and robots.

3. Documentation

HTTP Headers and the header() function in PHP

4. Alternatives

You may use the alternative method of http_redirect($url); which needs the PECL package pecl to be installed.

5. Helper Functions

This function doesn't incorporate the 303 status code:

function Redirect($url, $permanent = false)
{
    header('Location: ' . $url, true, $permanent ? 301 : 302);

    exit();
}

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

This is more flexible:

function redirect($url, $statusCode = 303)
{
   header('Location: ' . $url, true, $statusCode);
   die();
}

6. Workaround

As mentioned header() redirects only work before anything is written out. They usually fail if invoked inmidst HTML output. Then you might use a HTML header workaround (not very professional!) like:

 <meta http-equiv="refresh" content="0;url=finalpage.html">

Or a JavaScript redirect even.

window.location.replace("http://example.com/");

@Chuck Le Butt 2011-05-27 12:30:48

Some problems with this answer: 303 may not be the "correct" status code. 301 may be desired for Google, for example. Secondly, header('Location: '.$newURL); must be before any HTML (or text) has been passed to the browser, or it will not work correctly.

@MarioVilas 2014-04-27 13:57:46

Also, if the new URL is built by concatenating user input, some sanitization is in order. :)

@robertodecurnex 2014-07-17 04:09:37

The daily WTF story is a common one, sadly. Anyway, it's not the missing die what cause the problem but a bad design. Shutting the process violently is wrong in 99.9% of the cases. A common, cleaner solution (not my favourite anyways) is to throw a RedirectionException and catch it on you application entry point. After that you can have all your "after *" calls (logs/close connections/what ever)

@Timo002 2014-09-23 08:06:59

The http-equiv="Location" is not supported by all browsers. You should use refresh instead! <meta http-equiv="refresh" content="0;url=http://example.com/">

@madumlao 2014-12-12 09:47:06

Never issue a 301 unless you mean it. 301 means permanent, and permanent means permanent, meaning it will be cached by user agents, meaning long, caffeine-filled nights staring at application logs wondering if you're going insane because you swear some page should have been called or updated and you swear to God it works on your machine but not the client's. If you absolutely must call a 301, put a cache-control max-age on the resource. You don't have infinite wisdom and you shouldn't be acting like you do.

@ars265 2015-03-09 18:21:24

But is there a reason to use die over exit? exit seems cleaner and more appropriate.

@Christopher Schultz 2015-05-19 17:59:43

A note about PECL: PECL 2.x does not include http_redirect for some reason, so betting on http_redirect might be a mistake in the long-run.

@Nick Humphrey 2015-05-22 09:30:43

commenter @tgape in the WTF story says "exit()" should be used instead of "die()": <<If there is a die immediately after a header redirect, the code will always hit it, and your error logs will fill up with useless "errors">>

@rhavendc 2016-06-20 08:32:24

I'm wondering why all these codes are working fine in my localhost but failing when the system is up in a hosting site.. hmm..

@dpa 2016-11-18 12:56:30

6 solution is useful when need track redirects with client side tracking scripts, eg. google analytics.

@kris 2016-12-14 06:54:18

+1 for the Absolute URL information - that was causing my redirect to fail silently on chrome (well, actually I was missing "http://", but that pointed me in that direction).

@Mahdi Jazini 2017-01-03 12:21:29

don't forget to add header("Cache-Control: no-cache"); before the line

@RozzA 2017-07-07 03:26:24

I combined the header solution & using the die( "echo here" ) command to echo out meta refresh tag & all of the valid js solutions, should have me a pretty compatible little redirector!

@DanAllen 2017-11-16 01:43:15

I keep reading that sending a header in the midst of html streaming out will generate the "cannot modify header" error, but I have not seen that in awhile now. I have even cookies accepted by a browser after html has started running into it. I just setup up codepen with 150 lines of html interrupted by a header sent by php. I can't find any notice if a problem either in the php error log or Chrome inspector. codepen.io/danallenhtn/pen/ooGWgd

@Doktor J 2018-06-01 03:15:37

@DanAllen you may have output buffering on; since it's not actually outputting the data to the client as the code runs, it hits the header() call and tacks that on before flushing the buffer to the client.

@The Godfather 2018-08-13 12:29:23

Since July 2014 relative URLs are allowed in Location header. See recent update in answer stackoverflow.com/a/25643550/1657819 (refer tools.ietf.org/html/rfc7231#section-7.1.2)

@Ari Waisberg 2018-08-15 14:19:17

wtf??? the crawler can read php code??? I thought they read html and js... but if reads php means he is inside your server, that's not a crawler thats a virus and you have to worry a lot more than a "redirect"... I'm surprise none note this...

@Ehsan88 2019-04-17 03:21:01

I agree with @robertodecurnex. The problem with The Daily WTF story is that it uses redirection to prevent an unauthorized user from doing a deletion. That's an absolutely bad design. You should never rely on redirection to prevent anything.

@Jason 2019-05-10 09:31:09

If you are doing this in a framework, then die() or exit() is probably the last thing you should do. Check how you should exit cleanly from the framework so that it has a chance to log things, clean up, close files etc. Of course a framework will probably already have a helper function or method to do a redirect, but I'm mentioning this as it is good to not get into the habit of just doing an exit() without thinking about the consequences in the application.

@BugWhisperer 2019-08-07 01:00:52

is there any way to redirect before the browser detects the HTTP protocol? the reason i need to redirect is because i cannot get enough SSL certificates for all of my domains. i'd use .htaccess to redirect, but i need a way to somehow pass on which domain redirected to the final domain?

@jabko87 2017-10-13 10:56:05

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

Redirect 301 / http://new-site.com/

@joan16v 2015-01-12 11:03:32

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

@Hammad Khan 2014-06-27 07:24:59

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

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

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?

@Stathis Andronikos 2016-05-19 11:04:24

Simple and to the point answer! Great for a simple page redirection!

@Kai Noack 2016-08-28 18:33:00

And that way you do not run into the common Cannot modify header information - headers already sent by error.

@Istiaque Ahmed 2017-09-09 21:20:06

@hmd, what if javascript is disabled ?

@Hammad Khan 2017-09-10 17:55:41

@IstiaqueAhmed javascript is almost always enabled these days but if it it is disabled then you can use PHP buffer. This SO question answers that. If you are using PHP Buffering then you dont need this method I gueess.

@MestreLion 2018-08-04 08:45:42

False, you can (and should) do it in PHP even without buffering: in a well-designed page all relevant PHP processing should take place before any HTML content is sent to the user. That way PHP redirects will work fine.

@Luke 2014-01-15 04:21:54

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

@Alix Axel 2009-04-20 14:19:11

function Redirect($url, $permanent = false)
{
    if (headers_sent() === false)
    {
        header('Location: ' . $url, true, ($permanent === true) ? 301 : 302);
    }

    exit();
}

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

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

@Kuroki Kaze 2009-04-20 14:36:52

And don't forget output buffering or you'll end up with 'Headers already sent'.

@Strae 2009-04-20 15:49:05

... and dont forget th print out somthign like "you'll be redirected to $nepage in $n seconds, click $link here if redirect dont happen" Some broser, and some browser's settings, may fail that redirect.

@rmeador 2009-04-20 16:03:31

@DaNieL: this type of redirect won't take "$n seconds". It will be instant if it happens at all, and any conforming browser should handle it. I think you're thinking of the "meta refresh" redirects that people use when they don't know any better.

@Andrew Moore 2009-04-20 20:48:10

@rmeador... For older browsers and speciality browsers. You should first do your Location header, if fails have a meta-redirect with the "you'll be redirected to page in x seconds" with a link in case the meta-redirect fails. That's the proper and fail-safe way of doing a redirect.

@nickf 2009-04-21 00:57:07

which browsers are these?

@vartec 2009-04-21 07:56:48

Andrew: how can HTTP browser not respect Location:?

@markus 2009-04-21 12:37:01

does not incorporate the 303 status.

@Alix Axel 2009-08-13 06:54:44

@Kuroki Kaze: You won't end up with 'Headers already sent' because of the headers_sent() check.

@MarioVilas 2014-04-27 13:57:00

@vartec It doesn't have to be a browser, it could be a spider or a malicious user.

@MauganRa 2016-11-13 15:25:04

@MarioVilas why is a spider or a malicious user a problem? If the intention is to lead a visitor away from a confidential part of the site, then the app's design is quite flawed already...

@Tanner Summers 2016-11-20 03:28:52

why do we need the exit() or die()?

@MestreLion 2018-08-04 08:42:08

@TannerSummers: so no more processing is done on PHP and no content is displayed to the user. The former is potentially harmful (deleting records, etc) and hard to debug

@Henrik Paul 2009-04-20 20:25:12

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

@nickf 2009-04-20 14:24:47

Most of these answers are forgetting a very important step!

header("Location: myOtherPage.php");
die();

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.

@Strae 2009-04-20 15:50:34

What's about give some output to the user before kill the script? You know, people love to know what is happenin...

@vartec 2009-04-20 17:11:03

you're assuming that the script has nothing to do except redirect. Which might be not true at all.

@nickf 2009-04-21 00:56:03

@DaNieL: change it to die("Stop ignoring my headers!")

@TheBlackBenzKid 2015-06-02 05:46:01

I liked that simple explanation of die(); you gave - if you dont do it the user may see the complete page for a moment if you do use it; the user will be redirected and no temporary content glitch will show + 1

@DanAllen 2017-11-16 01:03:00

It is possible to have useful activity occur after the header is sent, activity that sends nothing to the browser, but logs the activity or finishes recording transactions. For this reason, the need for die/exit is depends on the script.

@Brent 2009-04-20 14:23:17

Like others here said, sending the location header with:

header( "Location: http://www.mywebsite.com/otherpage.php" );

but you need to do it before you've sent any other output to the browser.

Also, if you're going to use this to block un-authenticated users from certain pages, like you mentioned, keep in mind that some user agents will ignore this and continue on the current page anyway, so you'll need to die() after you send it.

@josh 2014-01-18 08:39:54

but you need to do it before you've sent any other output to the browser. Awesome!! Been searching for minutes on why I kept receiving the headers already sent error. +1!!

@MauganRa 2016-11-13 15:29:55

More general, you have /stop your script completely/. die() is just one way to do that.

Related Questions

Sponsored Content

58 Answered Questions

[SOLVED] How do I redirect to another webpage?

37 Answered Questions

[SOLVED] Deleting an element from an array in PHP

  • 2008-12-15 20:28:55
  • Ben
  • 2347965 View
  • 2298 Score
  • 37 Answer
  • Tags:   php arrays unset

18 Answered Questions

[SOLVED] Reference — What does this symbol mean in PHP?

15 Answered Questions

[SOLVED] Why shouldn't I use mysql_* functions in PHP?

  • 2012-10-12 13:18:39
  • Madara Uchiha
  • 206750 View
  • 2395 Score
  • 15 Answer
  • Tags:   php mysql database

28 Answered Questions

[SOLVED] How can I prevent SQL injection in PHP?

34 Answered Questions

[SOLVED] Reference - What does this error mean in PHP?

7 Answered Questions

[SOLVED] How does PHP 'foreach' actually work?

7 Answered Questions

[SOLVED] How can I redirect and append both stdout and stderr to a file with Bash?

31 Answered Questions

[SOLVED] How to manage a redirect request after a jQuery Ajax call

6 Answered Questions

[SOLVED] How do I redirect with JavaScript?

  • 2011-01-20 08:08:18
  • Ms_Lucky13
  • 1354803 View
  • 913 Score
  • 6 Answer
  • Tags:   javascript redirect

Sponsored Content