PHP code example of datahihi1 / tiny-env

1. Go to this page and download the library: Download datahihi1/tiny-env library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

datahihi1 / tiny-env example snippets



use Datahihi1\TinyEnv\TinyEnv;

// Load from the current directory
$env = new TinyEnv(__DIR__);
$env->load();


use Datahihi1\TinyEnv\TinyEnv;

// Load immediately upon instantiation
$env = new TinyEnv(__DIR__, true);

$env->lazy(['DB']); // Loads only variables starting with DB_
echo env('DB_HOST'); // Output: localhost
echo env('NAME', 'N/A'); // Output: N/A (NAME not loaded)

// Load only DB_HOST
$env->only('DB_HOST');

// Load only DB_HOST and DB_PORT
$env->only(['DB_HOST', 'DB_PORT']);

// After calling only(), only those variables are available in env()
echo env('DB_HOST'); // Output: localhost (if present in .env)
echo env('DB_PORT'); // Output: 3306 (if present in .env)


// Get a specific variable
echo env('NAME'); // Output: TinyEnv

// Get with a default value if the variable is not set
echo env('TESTER', 'Datahihi1'); // Output: Datahihi1 (if TESTER is not defined)

// Get all variables
print_r(env());


setenv('KEY', 'demo'); // Sets KEY=demo in $_ENV and .env file
echo env('KEY'); // Output: demo

validate_env([
    'VERSION' => ' exception if DB_PORT is not an integer
]);

$env->load();
print_r(env()); // Shows all variables from .env
$env->unload();
print_r(env()); // Empty array

$env->refresh(); // Equivalent to $env->unload()->load()
print_r(env()); // Updated variables from .env


use Datahihi1\TinyEnv\TinyEnv;

// Initialize and load
$env = new TinyEnv(__DIR__);
$env->load();

// Access variables
echo env('NAME', 'Unknown'); // TinyEnv
echo env('NOT_FOUND', 'Default'); // Default

// Set a new variable
setenv('APP_DEBUG', true);

// Validate
validate_env(['APP_DEBUG' => 'bool']);

// Refresh
$env->refresh();