Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mshakeel's avatar

Multi line environment variable

We are using https://github.com/layerhq/layer-identity-token-php to generate identity token and have added private key in .env file like following:

LAYER_PRIVATE_KEY=-----BEGIN RSA PRIVATE KEY-----
keyxxxxxxxxxxxxxxxxxxxxxxxxx-----------
-----END RSA PRIVATE KEY-----

but it only returns first line (i.e. -----BEGIN RSA PRIVATE KEY-----) and therefore identity token can't be generated.

Please help how to store this key within .env file

Setting this key within code like following is working fine but we want to store it in .env

$privateKey                 = <<<EOF
-----BEGIN RSA PRIVATE KEY-----
keyxxxxxxxxxxxxxxxxxxxxxxxxx-----------
-----END RSA PRIVATE KEY-----
EOF;
$layerIdentityTokenProvider->setPrivateKey($privateKey);
0 likes
12 replies
Snapey's avatar

have you tried quoting the entire string?

mshakeel's avatar

@Snapey I have tried quoting the entire string, '\n' & '' at the end of each line but nothing worked

mglinski's avatar

This thread is old as all hell but I need to do the same thing here. The solution is to embed \n in the string in your .env file and then str_replace('\\n', "\n", config('your_multiline_item')); when you retrieve it. Ideally you use something like a service provider to do this for you and you store the transformed version in the app container directly.

2 likes
BrendanTWhite's avatar

With apologies for raising this dead thread, but I had to embed \\n and not just \n in the string in my .env file. Otherwise it interpreted the \n as an actual newline character, even if I put it all in single quotes.

1 like
kedar's avatar

Ran into the same issue this morning, kind of odd that there isn't a better solution. As the previous commentators posted, the solution here is to replace

\n with \n and then in your .env file, quote the string, and use str_replace to transform \n back to \n when you use it.

boptom's avatar

This now works on new versions of Laravel and dotenvphp:

LAYER_PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----
keyxxxxxxxxxxxxxxxxxxxxxxxxx-----------
-----END RSA PRIVATE KEY-----"
2 likes
gonzalg's avatar

@boptom Just make sure you don't leave any spaces on the left side when pasting the key

dusterio's avatar

I created an open-source package to solve this today because I've been running into this issue a few times now: https://github.com/TixelRocks/long-env. Just replace env() with long_env() for any multi-line long environment variables that you have and everything will be taken care of automatically

1 like

Please or to participate in this conversation.