Sign Up

Sign In

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Sorry, you do not have a permission to ask a question, You must login to ask question.

How do I make a redirect in PHP?

  • 0

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.

Share

1 Answer

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

     

    • 0

Sorry, you do not have a permission to answer to this question.

close