Set $_SERVER variable when calling PHP from command line?

前端 未结 5 1992
有刺的猬
有刺的猬 2020-12-25 12:05

Is it possible to pass a $_SERVER variable to a PHP script via the command line?

Specifically I am trying to set the $_SERVER[\'recipient\'] manually so I can test e

相关标签:
5条回答
  • 2020-12-25 12:25

    You can also pass two and more variables. For example:

    $ SERVER_NAME="example.com" REQUEST_URI="?foo=bar" php script.php
    
    <?php
    
    print_r($_SERVER);
    
    0 讨论(0)
  • 2020-12-25 12:27

    How about setting up a dummy page called dummy.php with this contents:

    <?php
        $_SERVER['recipient'] = 'me@gmail.com';
    ?>
    
    0 讨论(0)
  • 2020-12-25 12:35

    On *nix:

    $ recipient="email@domain.com" php script.php
    
    <?php
    
    print_r($_SERVER);
    

    Test:

    $ recipient="email@domain.com" php script.php | grep recipient
    
    [recipient] => something@domain.com
    

    Or, you can export it or setenv (depending on your OS), like

    $ export recipient="email@domain.com"
    $ setenv recipient="email@domain.com"
    
    0 讨论(0)
  • 2020-12-25 12:39

    I personally use the following.

    Example: set $_SERVER['recipient] in my PHP command line.

    With OS X

    • Follow the instructions in https://github.com/ersiner/osx-env-sync
    • Append the following line to the file '~/.bash_profile' (create it, if it does not exist)

      export recipient="something@example.com"

    With Ubuntu GNU/Linux

    • Append the following line to the file '/etc/environment' (create it, if it does not exist, see https://help.ubuntu.com/community/EnvironmentVariables)

      recipient=something@example.com

    0 讨论(0)
  • 2020-12-25 12:43

    The answer by @sberry is correct.

    ...but because I came to this page looking for setting default values for the $_SERVER array, when running PHP from command line, here is my own answer. Hope it might help somebody.

    empty( $_SERVER['HTTP_HOST'] ) && $_SERVER['HTTP_HOST'] = 'localhost';
    empty( $_SERVER['REQUEST_URI'] ) && $_SERVER['REQUEST_URI'] = '/';
    empty( $_SERVER['DOCUMENT_ROOT'] ) && $_SERVER['DOCUMENT_ROOT'] = __DIR__;
    print_r( $_SERVER );
    
    0 讨论(0)
提交回复
热议问题