Search code examples
phpcodeignitercodeigniter-4dotenv

getenv() is some times returning false in CodeIgniter 4. Why?


I am loading table data fetched using Ajax in a table with datatables. The logic fetches some value from the .env file using getenv() function. This getenv() is returning false only some of the times and otherwise not.

I tried opening the URL (HTTP GET) which datatables use to fetch the data thru Ajax in a browser, and there it does not seem a problem at all.

public function ap_FetchData()
{
    $accountLibrary = new Account();
    if($accountLibrary->checkIsUserLogged())
    {
        // do some stuff and print JSON - dummy logic
        $data = [];
        for($i=1;$i<=10;$i++)
        {
            $image = getBucketURL($i.".jpg");
            $data[] = $image;
        }
        outPutAsJSON($data);
    }
    else outPutAsJSON("Your session is timed-out. Please login again.", 403);
}

Some times I get the JSON output with the Bucket URLs (partial) and sometimes I get session is timed-out error. However, this sessions timed-out behavior is seen only on the AJAX.

The checkIsUserLogged is at Account.php at Libraries directory

function checkIsUserLogged(): bool
{
    $sessionName = getenv("session.name"); // this is the session name stored in env file sometimes and false sometimes 
    // do validation and return true or false
}

The getBucketURL() is at a helper file.

function getBucketURL($key)
{
    return getenv("s3bucket.url").$key;
    /*
     * some times this return as http://www.example.com/$key
     * and
     * some times it return only $key
     * var_dump(getenv("s3bucket.url")) outputs (bool) false is second case
     */
}

Expected output:

{
    "http://www.example.com/1.jpg",
    "http://www.example.com/2.jpg",
    "http://www.example.com/3.jpg",
    .
    .
    "http://www.example.com/10.jpg"
}

Actual problematic Output:

{
    "1.jpg",
    "2.jpg",
    "3.jpg",
    .
    .
    "10.jpg"
}

Edit

$_SERVER["s3bucket.url], $_ENV["s3bucket.url] and $_SERVER["session.name], $_ENV["session.name] works perfect. Seems the problem is only with getenv()

Output


Solution

  • For a more 'bulletproof' solution, use CodeIgniter 4's helper function:

    env(string $key, $default = null).

    I.e:

    echo env("s3bucket.url");
    

    It first searches for the 'key' in the $_ENV variable, then the $_SERVER environment variable and lastly, the getenv(string $varname, bool $local_only = false) PHP function.


    EXCERPT FROM:

    https://github.com/codeigniter4/CodeIgniter4/blob/develop/system/Common.php

    
    if (! function_exists('env')) {
        /**
         * Allows user to retrieve values from the environment
         * variables that have been set. Especially useful for
         * retrieving values set from the .env file for
         * use in config files.
         *
         * @param string|null $default
         *
         * @return bool|string|null
         */
        function env(string $key, $default = null)
        {
            $value = $_ENV[$key] ?? $_SERVER[$key] ?? getenv($key);
    
            // Not found? Return the default value
            if ($value === false) {
                return $default;
            }
    
            // Handle any boolean values
            switch (strtolower($value)) {
                case 'true':
                    return true;
    
                case 'false':
                    return false;
    
                case 'empty':
                    return '';
    
                case 'null':
                    return null;
            }
    
            return $value;
        }
    }