Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I use environment variables (repl.it) to create an array?

If you’re not aware of this, environment variables are kind of like secret values in Repl.it as Repl.it makes your code publicly available for everybody.

I have a set of keys that I want to remain hidden on the website, and I want the website to randomize a key selection to distribute to the user on page load. Kind of a makeshift key system.

However, once I put the key values into the environment variable, and I try to load it into an array, this happens: https://i.imgur.com/sNFsdb6.png

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This, in basis, is the code I’m using (I load the varaible $trollitem for display later on in the code, but that’s just a bunch of HTML design)

<?php
  $loadstring = getenv('cheatxkeys');
  $items = array($loadstring);
  $trollitem = $items[array_rand($items)];
?>

And finally, this is how my environment variable looks: https://i.imgur.com/qaCZxOU.png

For obvious reasons, these are not the actual key codes I’m using, but rather a randomly generated amount of key codes to show what I’m trying to do.

If my post is unclear, please just comment, I really want to get this to work properly. Thanks!

>Solution :

Your environment variable $loadstring is stored and retrieved as a string, and PHP array() takes as parameters all the elements of the array to be created. Therefore, array($loadstring) gives an array of length 1 with the full string stored in the environment variable as its only element.

It appears your string format is like a JSON array, but without the enclosing square brackets, so you can do this:

$items = json_decode('[' . $loadstring . ']');

See also the json_decode documentation.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading