How to use a variable on multiple seperate pages?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
ShadowIce
Forum Commoner
Posts: 75
Joined: Tue Jan 12, 2010 8:43 am

How to use a variable on multiple seperate pages?

Post by ShadowIce »

How would I use this code to allow for me to use the same variable defined on the 1st page, on 2 or more seperate pages?

for instance, I wanted to print $foo on page 2, or page 4, but it is showing up as not there at all when I echo it.

test.php:

Code: Select all

<?php
function test() {
    $foo = "local variable";
 
    echo '$foo in global scope: ' . $GLOBALS["foo"] . "<br>\r\n";
    echo '$foo in current scope: ' . $foo . "<br>\r\n";
}
 
$foo = "Example content";
test();
?>
 
<form name="test" id="test" action="./vartest.php" method="POST">
 
<input type="submit" value="Submit">
 
</form>
vartest.php:

Code: Select all

<?php
    echo '$foo in global scope: ' . $GLOBALS["foo"] . "<br>\r\n";
    echo '$foo in current scope: ' . $foo . "<br>\r\n";
?>


The variables do NOT have to be in a function either.

Infact, I'd prefer if they weren't.

Thanks!

ShadowIce~
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: How to use a variable on multiple seperate pages?

Post by requinix »

Define $foo in one file, then include or require that file in other pages.

Code: Select all

<?php // foo.php
 
$foo = "some value";

Code: Select all

<?php
 
include "foo.php";
echo $foo;
ShadowIce
Forum Commoner
Posts: 75
Joined: Tue Jan 12, 2010 8:43 am

Re: How to use a variable on multiple seperate pages?

Post by ShadowIce »

What if it is a $_POST[] in the 1st page? THAT's what I'm after
User avatar
Jonah Bron
DevNet Master
Posts: 2764
Joined: Thu Mar 15, 2007 6:28 pm
Location: Redding, California

Re: How to use a variable on multiple seperate pages?

Post by Jonah Bron »

$_SESSION is what you're looking for.
Post Reply