简体   繁体   English

在另一页中包含表单数据

[英]Including form data in another page

When I post my form data: 当我发布表单数据时:

<form action="layouts.php" method="post">
  <input type="text" name="bgcolor">
  <input type="submit" value="Submit" align="middle">
</form>

to a php page, "layouts.php", it returns the string, as expected.: 到php页面“ layouts.php”,它按预期返回字符串:

$bgcolor = $_POST['bgcolor'];
echo $bgcolor; //returns "red"
echo gettype($bgcolor); // returns "string"

But when I include "layouts.php" in another page it returns NULL. 但是,当我在另一个页面中包含“ layouts.php”时,它将返回NULL。

<?php
  include("php/layouts.php");
  echo $bgcolor; //
  echo gettype($bgcolor); //returns "NULL"
?>

How do I pass the variable to another page? 如何将变量传递到另一页?

You'll have to use a session to have variables float around in between files like that. 您必须使用会话来使变量在这样的文件之间浮动。

It's quite simple to setup. 设置非常简单。 In the beginning of each PHP file, you add this code to begin a session: 在每个PHP文件的开头,添加以下代码以开始会话:

session_start();

You can store variables inside of a session like this: 您可以像这样在会话中存储变量:

$_SESSION['foo'] = 'bar';

And you can reference them across pages (make sure you run session_start() on all of the pages which will use sessions). 您可以跨页面引用它们(确保在将使用会话的所有页面上运行session_start() )。

layouts.php layouts.php

<?php 
session_start();
$bgcolor = $_POST['bgcolor'];
$_SESSION['bgcolor'] = $bgcolor;
?>

new.php new.php

<?php 
session_start();
echo $_SESSION['bgcolor'];
?>

Give the form two action="" and see what happens. 给表单两个action="" ,看看会发生什么。 I just tried that on a script of mine and it worked fine. 我只是在我的脚本上尝试过,效果很好。

A more proper way to solve this might exist, but that is an option. 可能存在解决此问题的更合适的方法,但这是一个选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM