Home » Php » PHP Pass Data with Redirect

PHP Pass Data with Redirect

Posted by: admin July 12, 2020 Leave a comment

Questions:

PHP Redirect with Post Data

Hi,

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:

if(isset($_SESSION['message'])){
    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']){

Answer:

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'];
}

Answer:

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:

http://www.php.net/manual/en/book.session.php

Here is a concise example:

Page 1

    session_start();

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

Page 2

    session_start();

    // Process POST data

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

    // Redirect to Page 1