2

I have a small bit of sample code to pull in the URI of a page. This page runs on a Linux/Apache installation:

$url = "";
if (!isset($_SERVER['REQUEST_URI'])) {
  echo "request_uri is not set";
  $url = "value could not be set, !isset on REQUEST_URI was true";
} else {
  $url = $_SERVER['REQUEST_URI'];
}
echo "url = $url <br />";

When I pull this page up in the browser, the code appears to have hit the "else" condition and I get the correct URI.

However, when I run this code directly from the command line using "php filename.php" the code appears to hit the if condition, where REQUEST_URI is not set. If I remove the "if" condition, I get the error "PHP Notice: Undefined index REQUEST_URI in..."

This is making me a little crazy! Is there a problem with REQUEST_URI? Why would it return different answers between the browser and the command line? Where can I go on the server to see if this value is actually set and returnable?

Thanks for any help you can provide.

thanksd
  • 54,176
  • 22
  • 157
  • 150
itrickski
  • 129
  • 3
  • 15
  • Comman line interface parameters are **not** URIs, since they do not follow the web addressing scheme. See: http://php.net/manual/de/reserved.variables.argv.php for how CLI parameters are provided in a php script. – hherger Feb 01 '16 at 18:05
  • it's clearly stated in the docs. The entries in this array ($_SERVER) 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 – Andreas Feb 01 '16 at 18:05

1 Answers1

4

If you call it from the browser you are making a REQUEST to a URI and then the HTTP server is executing the PHP program and telling it what that URI is.

If you call it from the command line, then there is no HTTP REQUEST and there is no URI (nor, for that matter is there a SERVER).

The behaviour you are getting is entirely expected.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • On CLI some SERVER elements are provided `$ env -i php -r 'var_dump($_SERVER);' array(9) { ["PHP_SELF"]=> string(1) "-" ["SCRIPT_NAME"]=> string(1) "-" ["SCRIPT_FILENAME"]=> string(0) "" ["PATH_TRANSLATED"]=> string(0) "" ["DOCUMENT_ROOT"]=> string(0) "" ["REQUEST_TIME_FLOAT"]=> float(1512626431.7066) ["REQUEST_TIME"]=> int(1512626431) ["argv"]=> array(1) { [0]=> string(1) "-" } ["argc"]=> int(1) }` – Szépe Viktor Dec 07 '17 at 06:01
  • Perfect answer. I NEEDED to hear this after wasting a day wondering why the $_SERVER values weren't set! – Jim Marquardt Jul 23 '21 at 15:55