Home » PHP

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

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.

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







Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.