Saturday, April 05, 2014

Pass variables between two PHP pages

1. Embed it as a hidden field in your form, or
 <input type=”hidden” name=”myVariable” value=”Your value” />
Now you can access in the page inside action with   the method GET/POST.
2. Add it your forms action URL
<form method="POST" action="Page2.php?myVariable1='xyz'.&myVariable2='abc'>
It will create a variable which will be accessible through $_GET[] array.
Example:
//Original page : t1.php
<html>
    <body>
<?php $x="Hello" ; ?> 
<a href="t2.php?v=<?php echo $x; ?>" >Hi</a>
   </body>
</html>
Next Page : t2.php
<?php
$x=$_GET['v'];
echo $x;
?>
3.Sessions/Cookie would be good choice for you.
Session:
//On page 1
$_SESSION['varname'] = $var_value;

//On page 2
$var_value = $_SESSION['varname'];
Remember to run the session_start() statement on both these pages before you try to access the $_SESSION array, and also before any output is sent to the browser.
Example: Code of page1.php
<?php                                    // page1.php
               session_start();
               echo 'Welcome to page #1';
               $_SESSION['favcolor'] = 'green';
               // Works if session cookie was accepted
               echo '<br /><a href="page2.php">page 2</a>';
?>
Code for Page2.php
<?php              // page2.php
               session_start();
               echo 'Welcome to page #2<br />';
               echo $_SESSION['favcolor']; // green
?>
Cookie:
//One page 1
$_COOKIE['varname'] = $var_value;

//On page 2
$var_value = $_COOKIE['varname'];
The big difference between sessions and cookies are that the value of the variable will be stored on the server if you're using sessions, and on the client if you're using cookies.
I can't think of any good reason to use cookies instead of sessions, except if you want data to persist between sessions, but even then it's perhaps better to store it in a DB, and retrieve it based on a username or id.
HTML / HTTP is stateless, in other words, what you did / saw on the previous page, is completely disconnected with the current page. Except if you use something like sessions, cookies or GET / POST variables. Sessions and cookies are quite easy to use, with session being by far more secure than cookies. More secure, but not completely secure.

No comments:

Post a Comment

Any Suggeston or Query ?