I need to share variables between PHP files in PHP 4.0.

I tried in two ways:

  1. use "global":

In a1.php:
global var1;
$var1 = 'some value';
...
Forward("a2.php");

In a2.php:
global var1;
echo $var1; //no out put here

  1. use $GLOBALS

In a1.php:
$GLOBALS['var1'] = 'some value';
...
Forward("a2.php");
In a2.php:
echo $GLOBALS['var1']; //no out put here

What's wrong with these two methods and how can I get "var1" be shared between "a1.php" and "a2.php"?

Thanks
Simon

    It all depends on what you want to do with the variable.

    Are you trying to pass the variable from a1.php to a2.php?

    If so, you need to create a form, and send the variable to a2.php, like this:

    Page=a1.php

    <form method=POST action="./a2.php">
    <input type=text name="var1" value="<? echo $var1; ?>">
    <input type=submit value=" Submit ">
    </form>

    Then on page=a2.php

    <?
    $var1 = $HTTP_POST_VARS["var1"];
    ?>

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    <HTML>
    <HEAD>
    </HEAD>

    <BODY>

    <? echo $var1; ?>

    </BODY>
    </HTML>

    This allows you to pass a variable from one page to another.

    Hope this helps.

      Making a variable global does not make it accessible from other scripts, it simply makes it accessible from within a function (in the same script).

      To pass data between scripts, you need to either save it in a file or a database, set a cookie, use sessions, or pass the data from one script to another in the url or using a hidden input in a form.

      Saving data in a file/database is what you should do if you want the variables to remain set for the script no matter who is viewing the page - for example, a hit counter.

      Setting a cookie or using sessions sets variables that can be accessed by any script on your site, but they work by storing information on the browser, so they are restricted to scripts called by the same user. An example of this is current login information for a user on a site.

      You can get a similar effect as cookies or sessions by passing data in the url. The advantage of this method is that it doesn't require cookie support on the browser, which is often disabled for secirity reasons.

        Write a Reply...