Ko Ko wrote:
Dear All,
I am wondering how to pass one variable from one php file to another
continuously or discontinuously.
For example, variable $a is declared in file1.php. I like to use that
variable in file2.php or file3.php where in file2.html, I won't use
that variable.
Looking forward to your help.
Thanks for your time and experience.
Hi,
You can pass variables from one PHP script to another in different ways.
1) use SESSION
If you use SESSION, you can easily store a value in it and retrieve it from
another PHP script.
script1.php
// sets and stores the variable
$a = 42;
$SESSION["myNumber"] = $a;
From script2.php:
echo "myNumber is $a";
2) POST the value to script2.php
If script1.php does NOT produce any output, and just want to call
script2.php, you can post to script2.php.
Remember that sccript1.php should stop doing anything that is relevant after
redirecting the browser to script2.php
You can also use querystring to pass information to script2.php (which is
easier)
From script1.php:
$a = 42;
$newLocation = "http://www.yoursite.org/script2.php?a=$a";
header ("Location: $newLocation");
exit;
From script2.php:
$a = "unknown";
if (isset($_GET["a"])) {
$a = $_POST["a"];
}
The above example uses $_GET. $_GET is called a superglobal and it contains
all name/value pairs found on the url (after the ?).
Note that if you need/want to pass information using POST, you must send a
form with method="POST", or use CURL. (See
www.php.net for details)
In that case the superglobal $_POST will contain all name/value pairs.
Hope this helps.
Good luck!
Regards,
Erwin Moller