Search code examples
phpapachedebian

PHP won't echo environment variables despite them appearing in var_dump


I have a Debian 12 server running Apache2 (virtual hosts) + PHP 8.2.

I am struggling to get PHP to read environment variables, and am testing using this code:

<?php
   $scriptUrl = $_ENV['SCRIPT_NAME'];
   echo "$scriptUrl";
?>

Strangely, nothing is printed on the page.

I have tried this with several other environment variables, such as SCRIPT_URL. I have also tried using the getenv('SCRIPT_URL') function to no avail.

I ran var_dump($_SERVER); which returned a large number of variables, including SCRIPT_NAME which was correct, however no PHP I try seems to be able to access any variables.

I imagine this is related to my Apache / virtual host / PHP configuration.


Solution

    1. Why do you expect SCRIPT_NAME to be set as an environment variable? You usually find that in the $_SERVER superglobal not in $_ENV. $scriptUrl = $_SERVER['SCRIPT_NAME']; should give you the expected results.

    2. Not all environment variables are necessarily populated to the superglobal. var_dump($_ENV) might show different (or no) results compared to var_dump(getenv());. See variables order for details.

    3. To see what's available try:

    var_dump($_ENV);
    
    var_dump(getenv());
    
    var_dump($_SERVER);