Q:

How to redirect to another page in PHP?

belongs to collection: PHP Miscellaneous

0

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.

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

PHP code with HTML 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>

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.

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

PHP Miscellaneous

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Getting current date & time in PHP... >>
<< How to pass values between the pages in PHP?...