Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Pass Data with Redirect

Tags:

php

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.

like image 621
Billy Martin Avatar asked Feb 17 '12 00:02

Billy Martin


People also ask

How pass data redirect in PHP?

Redirection from one page to another in PHP is commonly achieved using the following two ways: Using Header Function in PHP: The header() function is an inbuilt function in PHP which is used to send the raw HTTP (Hyper Text Transfer Protocol) header to the client.

How pass data redirect?

You need to use sessions to pass data when using redirect: return redirect('/fortest2')->with('data', 'some data'); Then get data from session: $data = session('data');

Can we send data on redirect?

As part of the URL Redirect, you can pass along data that pertains to that survey response. This includes data collected in the survey response or data stored in hidden values or email campaigns, such as User ID for panel companies.

How to redirect page in PHP with post data?

Now in PHP, redirection is done by using header() function as it is considered to be the fastest method to redirect traffic from one web page to another. The main advantage of this method is that it can navigate from one location to another without the user having to click on a link or button.


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

like image 190
Tim Avatar answered Oct 03 '22 01:10

Tim


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'];
}
like image 41
Motive Avatar answered Oct 03 '22 00:10

Motive