10

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.

Billy Martin
  • 257
  • 2
  • 3
  • 9

3 Answers3

13

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']){

Rahul Khosla
  • 190
  • 2
  • 15
Tim
  • 14,447
  • 6
  • 40
  • 63
11

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'];
}
Motive
  • 3,071
  • 9
  • 40
  • 63
5

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
Chris Hutchinson
  • 9,082
  • 3
  • 27
  • 33
  • You need to add `unset` to your Page 1, or else the message will display every time (see my previous answer) – Tim Feb 17 '12 at 00:13