0

Just learning about passing variables from page to page in php, and trying to find the best way to do so for me, as I have to pass ~10 variables between 5 pages. On the first page, does it make sense to have a form:

<form method="post">
    <input type="hidden" name="test" value="<?php $test ?>" />
</form>

Then on the next page could I receive this variable using POST? I would not like to have an ACTUAL form, just use it as a storage area for my variables. Also, what do I use for action= if the second page is called second.php.

Any help is appreciated, thanks

4

5 回答 5

7

简短回答:表单仅在提交时才有效。您可能想使用会话

更长的答案:

  • 没有用户输入的表单是没有意义的。这就是它存在的目的。
  • 表单上的action=属性反映了表单的提交位置。如果处理页面是,second.php那么action=属性应该指向那里。
  • 会话不是唯一的可能性。PHP也可以设置cookies,如果服务器不关心数据(仅作为媒介),可以使用HTML5的localStorage
于 2012-08-01T14:57:02.533 回答
3

确实,如果您需要在所有五个页面中传递 10 个变量,那么使用session可能会更好。$_SESSION只要会话保持活动状态,您就可以将它们全部存储为变量的一部分并从任何页面访问它们。

于 2012-08-01T14:57:22.750 回答
0

如果我正确理解了您的问题,您可以尝试以下方法来发布您的值,而无需表单出现在页面上或实际上根本不在页面上。您需要引用 jQuery 库才能使用此代码。

    function hiddenPost(param1) {
        $('<form />')
        .hide()
        .attr({ method: "post" })
        .attr({ action: "http://my-URL-here.com/SomePage.php" })
        .append($('<input />')
            .attr("type", "hidden")
            .attr({ "name": "post_data" })
            .val(param1)
        )
        .append('<input type="submit" />')
        .appendTo($("body"))
        .submit();
    }

您可以在您发布到的页面上检索 POST 值,就像它是带有表单标签的常规 POST 一样。

对于 PHP: var postData = $_POST["post_data"];

希望有帮助。

于 2012-08-01T15:08:48.983 回答
0

您不能使用 $_POST 变量在用户会话中存储数据。

你应该使用:

  • 会话
  • 饼干
  • HTML5 存储
于 2012-08-01T14:58:21.563 回答
0

这取决于您想做什么,您有多种选择: 1. 使用您概述的表格和帖子。在这种情况下,在第 1 页上,您的 action="second.php" 2. 使用 GET 通过 URL 传递数据 3. 会话,如前两篇文章所述 4. Cookie

于 2012-08-01T14:59:51.113 回答