user3304642
user3304642

Reputation: 191

How to share array in php script

I am beginner of php and mysql I would like to share php array defined in one script, which I want to access from another script here is a scenario

script1.php

<?php 
 echo '<html>
       <head></head>
       <body>
       <form action="script2.php" method="post" >
       .......
       ....... some input
       .......
       <button >Submit</button>
       </form>
       </body>
       </html>';
?>

script2.php

<?php
 ...........
 ...........
 some validation
 $age=array("Peter"=>"21","Ben"=>"45","Joe"=>"33");
 some variable
 $x = 'Peter'; $y= 'Ben';

 // click on button run script3.
 echo " <a href='script3.php?x=$x&y=$y'>
 <button>Submit</button></a>";
?>

script3.php

<?php

// Though I tried both require_once and include, I can't access array 'age' in script2
require_once('script2.php');
include('script2.php');

// Here I am getting all variable defined in button part in actual code, but can't access array
post_r($_GET);

// Here I want to access array age in script2
?>

Please note this is not actual script, but this is a problem I am facing, I have index file in which form is filled once after submit validation is done in second script, if validation is successful then button will appear, as soon as I click on button script3 will activate, here I am able to receive variables defined in script to but I am unable to access array defined in script2 though I tried both together as well individually these functions require_once and include.

So how to share array ? Kindly someone please give your little time for me, so that I can learn something...

Upvotes: 1

Views: 314

Answers (2)

Jaykishan
Jaykishan

Reputation: 1499

Script 1

session_start();
$_SESSION['key'] = insert_your_array;

Script 2

session_start();
your_data = $_SESSION['key'];

That's it.

Closing session

As soon as you finish using $_SESSION array, you would close the session. But if you don't close it, then it'll close after default expiration time or browser closes. Even you can also customize session time out.

Function for closing PHP session, session_close()

Upvotes: 1

AbraCadaver
AbraCadaver

Reputation: 78994

You can use sessions to access the array in the next page, or use echo http_build_query($age); to add it to the link URL or you can put the array in a file and include it when needed in different files.

Upvotes: 1

Related Questions