Deepzz
Deepzz

Reputation: 4571

How to declare an array as global in PHP?

I need to write the contents of an array to a file, each time the page is loaded... I've created the array in index.php and pushing contents to the array in another ajax page.. But i couldn't access the array globally.. its showing an error as 'undefined variable $arr'..

Here's my code..

Index.php page...

<?php
    $arr = array();

    $ourFileName = "saved_data.txt";
    $ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");
    fwrite($ourFileHandle, "");

?>

Ajax page.....

<?php
    $name_full = $_GET['name_full'];
    $arr = $_GET['$arr'];

    array_push($arr,$name_full);
    /*------------To create a file-----------------*/
    $ourFileName = "saved_data.txt";
    $ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");
    /*---------To save data in the file------------*/
    foreach($arr as $key => $value)
    {
        fwrite($ourFileHandle, $value);
    }
    fwrite($ourFileHandle, ',');
    fclose($ourFileHandle);
    echo $name_full;
?>

what else should i do to make this array global...

Upvotes: 4

Views: 1092

Answers (3)

Wenhuang Lin
Wenhuang Lin

Reputation: 214

have you included the index.php in ajax.php?if you have include index.php,then do as "Sabin" says. i don't understand what you want to do.remember that every time you call a php file,it has no matter with previous php file.if you want a global variety in your site,use db will be better

Upvotes: 1

Evan
Evan

Reputation: 3306

Yeah, variables "expire" after each page is loaded. If you need some data to persist between requests, you have a few options:

  • pass the data to the client (perhaps in a hidden form field), and the have them re-submit it (accessible via GET/POST). This is bad because it's easy for the user to manipulate this data client-side
  • store the variables in $_SESSION which will persist for the user. This is bad because if you have more than one server, data won't be accessible on the other servers (unless you do some fancy load-balancing to ensure clients hit the same server each time)
  • use a 'temporary' store (memcache, redis) which is available to all servers
  • user s 'persistant' store (mySQL, mongo) which is available to all servers

Upvotes: 2

WatsMyName
WatsMyName

Reputation: 4478

in ajax page declare $arr as, global $arr; and see if this works, but i doubt this don't work because each time the page is loaded, the array gets reset, Why dont you use session for this?

Upvotes: 2

Related Questions