PHP Pass Data with Redirect

前端 未结 3 1289
北恋
北恋 2020-12-06 12:53

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.

  • pa
相关标签:
3条回答
  • 2020-12-06 13:25

    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'];
    }
    
    0 讨论(0)
  • 2020-12-06 13:29

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

    0 讨论(0)
  • 2020-12-06 13:41

    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
    
    0 讨论(0)
提交回复
热议问题