Home » Php » PHP Pass Data with Redirect

PHP Pass Data with Redirect

Posted by: admin July 12, 2020 Leave a comment


PHP Redirect with Post Data


I am a newbie PHP programmer and trying to code a small blog.

I will explain what I am trying to do.

  • page1.php: Has a table of all posts in the blog
  • page2.php: This page has a form where you can add a Post

Page 2 posts to itself and then processes the data, if it successful then uses header() to redirect back to page1 which shows the table.

Now what I want to do is to be able to have a small message on page 1 above the table saying your blog post has been successfully submitted but I’m not sure how I can pass data back to page 1 after the form processing.

How to&Answers:

Set it as a $_SESSION value.

in page2:

$_SESSION['message'] = "Post successfully posted.";

in page1:

    echo $_SESSION['message']; // display the message
    unset($_SESSION['message']); // clear the value so that it doesn't display again

Make sure you have session_start() at the top of both scripts.

EDIT: Missed ) in if(isset($_SESSION['message']){


You could also just append a variable to the header location and then call it from the page.

header('Location: http://example.com?message=Success');

Then wherever you want the message to appear, just do:

if (isset($_GET['message'])) {    
   echo $_GET['message'];


A classic way to solve this problem is with cookies or sessions; PHP has a built-in session library that assists with the creation and management of sessions:


Here is a concise example:

Page 1


    if (isset($_SESSION['message'])) {
       echo '<div>' . $_SESSION['message'] . '</div>';

Page 2


    // Process POST data

    $_SESSION['message'] = 'Hello World';

    // Redirect to Page 1