Transfer Variables Between PHP Pages

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.

How to pass variables between php scripts?

To pass info via GET:

    header('Location: otherScript.php?var1=val1&var2=val2');

Session:

    // first script
session_start();
$_SESSION['varName'] = 'varVal';
header('Location: second_script.php'); // go to other

// second script
session_start();
$myVar = $_SESSION['varName'];

Post: Take a look at this.

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

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>

How to pass variables between 2 PHP files?

The simplest solution is to append a paramter to the url

<a href="two.php?clicked=1">Click here for 1.</a>
<a href="two.php?clicked=2">Click here for 2.</a>

then in PHP

if (isset($_GET['clicked'])) {
$clicked = (int)$_GET['clicked'];
} else {
$clicked = 0;
}

Transfer variables between PHP pages

Try changing your session code as this is the best way to do this.

For example:

index.php

<?php
session_start();

if (isset($_POST['username'], $_POST['password']) {
$_SESSION['username'] = $_POST['username'];
$_SESSION['password'] = $_POST['password'];
echo '<a href="nextpage.php">Click to continue.</a>';
} else {
// form
}
?>

nextpage.php

<?php
session_start();

if (isset($_SESSION['username'])) {
echo $_SESSION['username'];
} else {
header('Location: index.php');
}
?>

However I'd probably store something safer like a userid in a session rather than the user's login credentials.

how to pass variables between 2 php files

login.php

<?php
include("authenticate.php");

That essentially acts like pasting the contents of authenticate.php inside login.php so although it's technically 2 files, it acts as if it's just the one - however $data is defined within the authenticate() function and so is only scoped within that function.



In authenticate.php - return the data from the function

// verify user and password
if($bind = @ldap_bind($ldap, $user, $password))
{
$result = ldap_search($ldap,$ldap_dn, "(cn=*)") or die ("Error in search query: ".ldap_error($ldap));
$data = ldap_get_entries($ldap, $result);
// echo $data["url"]; // I assume this is just for debugging...

// return $data from the function which should be "truthy"
return $data;
}
else
{
// invalid name or password
return false;
}



In login.php - evaluate the return from the authenticate() function - since PHP is loosely typed any (non-empty) string returned by the function can be evaluated as being "truthy" - the only other returns you have from the function are false so...

// run information through authenticator
if($authData = authenticate($_POST['userLogin'],$_POST['userPassword']))
{
// authentication passed
// renamed the variable $authData just for clarity
header("Location: authenticate.php?$authData");
die();
}

else {
// authentication failed
$error = "Login failed: Incorrect user name, password, or rights<br />";
}

PHP, getting variable from another php-file

You can, but the variable in your last include will overwrite the variable in your first one:

myfile.php

$var = 'test';

mysecondfile.php

$var = 'tester';

test.php

include 'myfile.php';
echo $var;

include 'mysecondfile.php';
echo $var;

Output:

test

tester

I suggest using different variable names.



Related Topics



Leave a reply



Submit