How to Pass Data Between Pages in PHP

How do I pass data between pages in PHP?

PHP is stateless unless you save things in session (which isn't secure right?)

You would need to make page2.php read all the values from page1.php and store them either in a server side state (session) or a client state (cookies or maybe hidden fields in the form)

If you want any of this secure or a secret, then you have to consider all of that as well. Nothing I explained is secret or secure in any way.

EDIT: here is an example of page1.php that sends the values of page1.php to page2.php as get parameters. You can do this with hidden fields, cookies or sessions as well.

What is important to remember is that page2.php is totally unaware of page1.php, and can't get to the values like you could it forms programming. Each page starts and ends it's life by the time you see a full web page, so you have to use some extra tricks to keep values. Those tricks are sessions, cookies, form posts, or gets.

<html>
<head>
<title>Page 1</title>
</head>
<body>
<?php
//set defaults assuming the worst
$total = 0;
$one =0;
$two=0;

//verify we have that value in $__POST
if (isset($_POST['submit']))
{
$submit = $_POST['submit'];
//If it is true, try some math
if($submit == "sub-total")
{
if (isset($_POST['one']))
{
$one = $_POST['one'];
//Add checks to see if your values are numbers
if ( ! is_numeric($one)) { $one = 0;}
}

if (isset($_POST['two']))
{
$two = $_POST['two'];
if ( ! is_numeric($two)) { $two = 0;}
}
$total = $one + $two;
echo " Your Price is \$ " .number_format ($total, 2, '.', ','). "<BR>";
}
if($submit == "submit" )
{
//go to page two, with the total from page1.php passed as a $__GET value
header("Location: page2.php?total=".$total);
}
}
?>
<form method="post" action="page1.php?submit=true">
<input type="text" name="one" id="one" value="<?=$one?>"/>
<input type="text" name="two" id="two" value="<?=$two?>"/>
<input type="submit" name="submit" value="sub-total" />
<input type="submit" name="submit" value="submit" />
</form>
</body>
</html>

PHP Pass variable to next page

HTML / HTTP is stateless, in other words, what you did / saw on the previous page, is completely unconnected 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.

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.

Cookie:

//One page 1
$_COOKIE['varname'] = $var_value;

//On page 2
$var_value = $_COOKIE['varname'];

The big difference between sessions and cookies is 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.

GET and POST

You can add the variable in the link to the next page:

<a href="page2.php?varname=<?php echo $var_value ?>">Page2</a>

This will create a GET variable.

Another way is to include a hidden field in a form that submits to page two:

<form method="get" action="page2.php">
<input type="hidden" name="varname" value="var_value">
<input type="submit">
</form>

And then on page two:

//Using GET
$var_value = $_GET['varname'];

//Using POST
$var_value = $_POST['varname'];

//Using GET, POST or COOKIE.
$var_value = $_REQUEST['varname'];

Just change the method for the form to post if you want to do it via post. Both are equally insecure, although GET is easier to hack.

The fact that each new request is, except for session data, a totally new instance of the script caught me when I first started coding in PHP. Once you get used to it, it's quite simple though.

Pass variables between two PHP pages without using a form or the URL of page

Sessions would be good choice for you. Take a look at these two examples from PHP Manual:

Code of page1.php

<?php
// page1.php

session_start();

echo 'Welcome to page #1';

$_SESSION['favcolor'] = 'green';
$_SESSION['animal'] = 'cat';
$_SESSION['time'] = time();

// Works if session cookie was accepted
echo '<br /><a href="page2.php">page 2</a>';

// Or pass along the session id, if needed
echo '<br /><a href="page2.php?' . SID . '">page 2</a>';
?>

Code of page2.php

<?php
// page2.php

session_start();

echo 'Welcome to page #2<br />';

echo $_SESSION['favcolor']; // green
echo $_SESSION['animal']; // cat
echo date('Y m d H:i:s', $_SESSION['time']);

// You may want to use SID here, like we did in page1.php
echo '<br /><a href="page1.php">page 1</a>';
?>

To clear up things - SID is PHP's predefined constant which contains session name and its id. Example SID value:

PHPSESSID=d78d0851898450eb6aa1e6b1d2a484f1

Can I eliminate use of hidden form fields in html to pass data between pages where the data is row id of all table rows

Actually, you can do this with a session variable.

Put all the order IDs in an array in the session. Instead of putting the order ID in the hidden input, put the array index.

$myorders = [];
$order_index = 0;
echo '<table class="table"><tr>
<th>Order Submitted on</th>
<th>Get Details</th>
</tr>';
while ($row = $ordersByUser->fetch(PDO::FETCH_ASSOC)) {
$myorders[$order_index] = $row['id'];
echo '<tr><td>'.$row['timestamp'].'</td>';

echo '<td><form method="POST" action="generateorderpdf.php">
<input type ="hidden" name="orderid" value="'.$order_index.'">
<input type="submit" value="CLICK" class="btn btn-dark">
</form></td></tr>';
$order_index++;
}
echo '</table>';
$_SESSION['myorders'] = $myorders;

Then in generatorderpdf.php, you use $_SESSION['myorders'][$_POST['orderid']] to get the order ID.

How to bring data to another page in php

You could store the variable in the class and then use a getter method to get that data back.
file1.php

if(isset($_POST['submit'])){
$data = new MyData($_POST['test']);
}

class MyData{
private $data = '';

function __construct($test){
***some process***
$data = $test;
}
function getData() {
return $this->data;
}
}

file2.php

    include file1.php;
echo $data->getData();

passing variable between pages

It depends on your needs, really, If you are passing search arguments between pages, for example, and the variables should be both persistent and be available to the end user (via bookmarking, for example), then pass them in the URL (but don't usually use quotes like you have around $id in "input_obj.php?id='$id'&method=plain)

If you are truly passing internal variables between scripts, this is better done via $_SESSION variables. Remember that end users can easily modify variables passed through URLs. Unless they are intended for use by the end user, that may be a real problem. By using $_SESSION, you insulate your script's variables from tampering by the end user when it's necessary to insulate them. (unless, of course, the variables are produced by other user input via GET/POST/COOKIE)

//page1.php
session_start();
$_SESSION['id'] = $id;

//page2.php
session_start();
echo $_SESSION['id'];


Related Topics



Leave a reply



Submit