Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set $_SERVER variable when calling PHP from command line?

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.

like image 322
Ian McIntyre Silber Avatar asked May 24 '12 04:05

Ian McIntyre Silber


People also ask

What is $_ server [' Script_name ']?

$_SERVER is an array containing information such as headers, paths, and script locations. The entries in this array are created by the web server. There is no guarantee that every web server will provide any of these; servers may omit some, or provide others not listed here.

What is $_ server [' Php_self ']?

$_SERVER['PHP_SELF'] Returns the filename of the currently executing script. $_SERVER['GATEWAY_INTERFACE'] Returns the version of the Common Gateway Interface (CGI) the server is using.

What is $_ server [' Request_uri ']?

$_SERVER['REQUEST_URI'] contains the URI of the current page. So if the full path of a page is https://www.w3resource.com/html/html-tutorials.php, $_SERVER['REQUEST_URI'] would contain /html/html-tutorials. php.


2 Answers

On *nix:

$ recipient="[email protected]" php script.php  <?php  print_r($_SERVER); 

Test:

$ recipient="[email protected]" php script.php | grep recipient  [recipient] => [email protected] 

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

$ export recipient="[email protected]" $ setenv recipient="[email protected]" 
like image 86
sberry Avatar answered Sep 28 '22 17:09

sberry


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 ); 
like image 43
tivnet Avatar answered Sep 28 '22 16:09

tivnet