简体   繁体   中英

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.:

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

But when I include "layouts.php" in another page it returns 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:

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).

layouts.php

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

new.php

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

Give the form two action="" and see what happens. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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