PHP 通过重定向传递数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9321071/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 06:33:52  来源:igfitidea点击:

PHP Pass Data with Redirect

php

提问by Billy Martin

PHP Redirect with Post Data

PHP 重定向与发布数据

Hi,

你好,

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

我是一个新手 PHP 程序员,正在尝试编写一个小博客。

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
  • page1.php:有一个包含博客中所有帖子的表格
  • page2.php:此页面有一个表单,您可以在其中添加帖子

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.

第 2 页发布到自身,然后处理数据,如果成功则使用 header() 重定向回显示表的 page1。

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.

现在我想要做的是能够在表格上方的第 1 页上显示一条小消息,说您的博客文章已成功提交,但我不确定如何在表单处理后将数据传递回第 1 页。

回答by Tim

Set it as a $_SESSIONvalue.

将其设置为$_SESSION值。

in page2:

在第 2 页:

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

in page1:

在第 1 页:

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.

确保您session_start()在两个脚本的顶部都有。

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

编辑:错过了)if(isset($_SESSION['message']){

回答by Motive

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

回答by Chris Hutchinson

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:

解决此问题的经典方法是使用 cookie 或会话;PHP 有一个内置的会话库,可以帮助创建和管理会话:

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

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

Here is a concise example:

这是一个简洁的例子:

Page 1

第 1 页

    session_start();

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

Page 2

第2页

    session_start();

    // Process POST data

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

    // Redirect to Page 1