How to redirect to another page in PHP?

Learn: How to redirect to another page in PHP? This article contains complete tutorial on redirection in PHP, which you can use to redirect from one page to another.
Submitted by Abhishek Pathak, on July 18, 2017 [Last updated : March 14, 2023]

What is Redirection?

Redirection is an integral part of modern website. If something happens on your website like a user submitted a comment or logged in, he should be redirected to thank you page or user profile page respectively.

Redirecting to another page

PHP provides a simple and clean way to redirect your visitors to another page that can be either relative or can be cross domain.

Here is a simple redirection script that will redirect to thank you page if the comment is submitted successfully. We will use the header('location: thankyou.html')function to redirect to the thank you page. The location is the parameter along with the path to file in the header() function.

PHP code to redirect to another page

<!DOCTYPE html>
<html>
<head>
    <title>Page Title</title>
</head>
<body>

<?php
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        $comment = $_POST['comment'];
        $name = $_POST['name'];
        
        if($comment && $name) {
            header('location: thankyou.html');
        }
    }
?>

    <form action="comment.php" method="POST">
        <input type="text" name="Name">
        <textarea name="comment"></textarea>
        <input type="submit" value="submit">  
    </form>   

</body>
</html>

Explanation

This is a simple PHP script, so we put a form that inputs a name and comment. In the PHP script we check if the server request method is post because we don’t want this code to execute if user hasn’t submitted the form through POST method, which is only possible if he submit the form.

Next, we store the values received in $comment and $name variables. Then we check if they are not empty, that is they have some value, then we redirect the visitor to thankyou.html page.

<!DOCTYPE html>
<html>
<head>
    <title>Page Title</title>
</head>
<body>

    <p>Thank you!</p>

</body>
</html>

So this is how you redirect to another page using header() function in PHP.

In the above example, we used the following PHP topics:

The thank you page contains a simple thank you message in html file, since it is just for display.

More PHP Programs »

All PHP Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.