Code Snippets

Get variables from a .env file using this great open source class. Automatically store them as their variable name. | php

Ideally, you want to store your variables like DB login, IPs, secret keys in a protected .env file on your server. Then you can edit it without having to modify the application code.

// // NB. uses: - this guy kicks ass, go visit and follow

// // Assumes a composer installation

require 'vendor/autoload.php'; // // if you use composer you'll have done this anyway

$dotenv = new Dotenv\Dotenv(__DIR__,'MYFILENAME.env'); // // don't just call it .env, give it some extra security incase someone screws up the .htaccess and allows access to the .env by mistake or something

// // $s3_bucket = getenv('S3_BUCKET'); // commented out, just an example of how you can access an individual var in the .env

// // instead, I am going to load all the variables as below.   Beware of variable name collisions if you are modifying an existing app

foreach ($_ENV as $key => $value) {

  // //echo "$key => $value<br />";  // <--- enable this if you want to see the output, or better yet put it in your debugbar on your dev server

  $$key = $value; // // assign every .env variable into the global space

* SO, say in our .env we have:
* S3_BUCKET="mybucket"
* we now have the variable $S3_BUCKET ready to use anywhere in our php app
* try it: echo $S3_BUCKET;

Published: Sun 24th December 2017
||COMMENTS|| This site proudly uses PrismJS to display code snippets

If you like this page, please share it.

Code Links - PHP, JS, CSS, Bootstrap, Bash, Emmet, IntelliJ, Sublime etc.

My personal list of links which I keep here publicly incase they help someone else one day.

Code Snippets

Snippets of PHP code I have gathered over the years. I keep them here for my own repository but also to share with others. I always link back when I remember the source.

My Github Repos

A work in progress. I am going to make as many modules that I write in my devbox public as possible.

Kit's Homepage

This site was originally intended as a test bed for code. It now includes my blog about business and powerlifting, as well as games for Spanish language learning

© 2018