html - How do I pass an Object between Web Pages through POST in PHP? -
is possible pass object through hidden field in html form using $_post , retrieve object on page form links to?
on first page, have form 1 below:
<?php session_start(); require_once '../model/player.php'; // enable creation of new player object $playername = filter_input(input_post, 'playername'); $playernumber = 1; $player = new player($playername, $playernumber); if (isset($player)) { echo '<p>successfully created player!</p><br>'; ?> <form class="viewstats" action="../view/displayplayerstatsview.php" method="post"> <input type="hidden" name="playerobject" value="<?php echo $player; ?>"> <input type="submit" value="view player's stats"> </form> <?php } ?>
and on second (receiving) page, have code code below:
session_start(); require_once '../model/player.php'; // use player object $player = filter_input(input_post, 'playerobject'); // error: thinks player object string.
my error seems receiving page retrieves 'playerobject' $_post array acting object string.
can give me guidance on how pass object 1 page using $_post array? possible? thank in advance.
update: based on suggestions serialize object, getting following errors:
if change code on first (sending) page to:
$playerserial = serialize((object) $player); <form class="viewstats" action="../view/displayplayerstatsview.php" method="post"> <input type="hidden" name="playerobject" value="<?php echo $playerserial; ?>"> <input type="submit" value="view player's stats"> </form>
and change code on second (receiving) page to:
$playerserial = filter_input(input_post, 'playerobject'); print_r($playerserial); $player = unserialize($playerserial);
then output print_r($playerserial);
o:6:
, know incorrect since object has properties holding player's name, number, health, strength, etc.
the require_once '../model/player.php';
code exists in both php files, , comes right @ top of both before other code executed.
you have make few additions , corrections:
<?php //... previous code $player = serialize($player); ?> <form class="viewstats" action="../view/displayplayerstatsview.php" method="post"> <input type="hidden" name="playerobject" value="<?php echo $player; ?>"> <input type="submit" value="view player's stats"> </form>
use serialize() function create string can passed other page can unserialize() follows:
secondpage.php:
$player = $_post['playerobject']; $player = unserialize($player);
also, forgot use echo here:
change
value="<?php $player ?>"
to
value="<?php echo $player; ?>"
Comments
Post a Comment