tags:

views:

300

answers:

3

In PHP I want to be able to set a variable value "superglobally" - that is a me-defined value that is accessible to EVERY script that runs on the server at its FIRST line of code (i.e. without having to require_once() anything or anything like that).

Currently I'm using $_ENV[ 'varname' ] by setting an environment variable on my system called varname. But it requires a reboot to make a change to the variable value on a Windows system, which is not good.

Are there any other solutions short of modifying php source?

+4  A: 

You can use the php.ini setting auto_prepend_file for this task. It allows you to specify an PHP script that is run just before any 'normal' PHP script is executed.

To quote the manual:

auto_prepend_file string

Specifies the name of a file that is automatically parsed before the main file. The file is included as if it was called with the require() function, so include_path is used.

The special value none disables auto-prepending.

To make a variable a super-global there, just extend one of the other super-globals, like you did with $_ENV, e.g.,

<?php
$_ENV['mystuff'] = "Hello World!";
$_SERVER['FOO'] = "BAR";
?>

Cheers,

Boldewyn
+5  A: 

Hi,

If you are using Apache, you could take a look at mod_env

It will allow you to use the SetEnv directive in Apache's configuration (and in .htaccess files, if your Apache server is configured so you can use those), like this :

In my Apache's file :

<VirtualHost *>
        ServerName      tests
        DocumentRoot /home/squale/developpement/tests

        ....

        SetEnv MY_TEST_VARIABLE "Hello, World!"

        ....

</VirtualHost>

(Require's an Apache restart to be taken into account)

Or in an .htaccess file :

SetEnv MY_OTHER_TEST_VARIABLE "This is looking nice !"

(Immediatly taken into account)

And, then, these variables are available in $_SERVER :

var_dump($_SERVER);

Gives me :

array
  'MY_TEST_VARIABLE' => string 'Hello, World!' (length=13)
  'MY_OTHER_TEST_VARIABLE' => string 'This is looking nice !' (length=22)
  'HTTP_HOST' => string 'tests' (length=5)
  'HTTP_USER_AGENT' => string 'Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.1.1) Gecko/20090716 Ubuntu/9.04 (jaunty) Shiretoko/3.5.1' (length=105)
  'HTTP_ACCEPT' => string 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' (length=63)
  'HTTP_ACCEPT_LANGUAGE' => string 'en-us,en;q=0.5' (length=14)
  ....
  ....

It's not $_ENV like you requested... But almost ;-)
And the idea is really the same ^^

Pascal MARTIN
+2  A: 

You can set a value in your php.ini which you can then retrieve with get_cfg_var.

troelskn