29

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 email piping without setting up a mail server.

Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109
Ian McIntyre Silber
  • 5,553
  • 13
  • 53
  • 76
  • not a very clear question but perhaps you want: php script.php command_line_arguments_go_here –  May 24 '12 at 04:48

4 Answers4

43

On *nix:

$ recipient="email@example.com" php script.php

<?php

print_r($_SERVER);

Test:

$ recipient="email@example.com" php script.php | grep recipient

[recipient] => something@example.com

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

$ export recipient="email@example.com"
$ setenv recipient="email@example.com"
Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109
sberry
  • 128,281
  • 18
  • 138
  • 165
3

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 );
tivnet
  • 1,898
  • 17
  • 19
0

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

cgaldiolo
  • 3,497
  • 1
  • 20
  • 17
0

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);
frops
  • 2,196
  • 4
  • 29
  • 42