88

I'm trying out the PHP micro Framework Lumen (from Laravel).

One of my first steps was to look into the .env.example file and make a copy of it to have my .env file. There is a variable APP_KEY just like there is in Laravel. Now I tried out the simple command php artisan key:generate to get my new key But I ran into the following error message:

[InvalidArgumentException] There are no commands defined in the "key" namespace.

Does some one know how I can generate keys for Lumen?

Update with solution

So I found my favorite solution for this problem. On the command line (Linux) I run php -r "echo md5(uniqid()).\"\n\";" what gives me something like this 7142720170cef01171fd4af26ef17c93.

If you are going to use Lumen more often, you may want to create an alias in your .bashrc, which is located in your home directory /home/USERNAME. To do so, you can open the file with nano ~/.bashrc or vi ~/.bashrc and copy the following alias at the end of the file, alias phpkey='php -r "echo md5(uniqid()).\"\n\";"'. Now you can use the command phpkey which will give you a 32 character long random string :)

Derk Jan Speelman
  • 11,291
  • 4
  • 29
  • 45
Thomas Venturini
  • 3,500
  • 4
  • 34
  • 43
  • 1
    Using a fast hash function, like md5, does not increase entropy and `uniqid` is a low-entropy source of "randomness". Please use the solution provided by @lukasgeiter as `str_random` draws bytes from a cryptographically secure random number generator. – Michael Cordingley Jun 29 '18 at 20:21

15 Answers15

148

The Laravel command is fairly simple. It just generates a random 32 character long string. You can do the same in Lumen. Just temporarily add a route like this:

$router->get('/key', function() {
    return \Illuminate\Support\Str::random(32);
});

Then go to /key in your browser and copy paste the key into your .env file.
Afterwards remove the route.

Obviously you could also use some random string generator online. Like this one

halloei
  • 1,892
  • 1
  • 25
  • 45
lukasgeiter
  • 147,337
  • 26
  • 332
  • 270
42

Firstly, you have to register your key generator command, put this Lumen Key Generator Commands to app/Console/Commands/KeyGenerateCommand.php. To make this command available in artisan, change app\Console\Kernel.php:

/**
 * The Artisan commands provided by your application.
 *
 * @var array
 */
protected $commands = [
    'App\Console\Commands\KeyGenerateCommand',
];

After that, configure your application so that Illuminate\Config\Repository instance has app.key value. To do this, change bootstrap/app.php:

<?php

require_once __DIR__.'/../vendor/autoload.php';

Dotenv::load(__DIR__.'/../');

/*
|--------------------------------------------------------------------------
| Create The Application
|--------------------------------------------------------------------------
|
| Here we will load the environment and create the application instance
| that serves as the central piece of this framework. We'll use this
| application as an "IoC" container and router for this framework.
|
*/

$app = new Laravel\Lumen\Application(
    realpath(__DIR__.'/../')
);

$app->configure('app');

After that, copy your .env.example file to .env:

cp .env.example .env

Ignore this step if you already use .env file.

Enjoy you key:generate command via:

php artisan key:generate

Edit

You may use Lumen Generator. It covers so much commands you are missing from Laravel.

krisanalfa
  • 6,268
  • 2
  • 29
  • 38
  • 2
    I would go with this answer rather, it's the laravel implementation and it teaches you a bit about console commands are structured and where they go in the context of your app. It is really cool once you dive into it :D – Etienne Marais Feb 10 '16 at 18:38
  • 2
    Nice solution! thanks for sharing. One tiny thing: I would use KeyGenerateCommand::class instead of the hardcoded class name in `$commands` ;) – itsjavi Apr 17 '16 at 01:26
  • 1
    this won't work if key was empty. Use this to replace the key: str_replace('APP_KEY='.env('APP_KEY'), 'APP_KEY='.$key, file_get_contents($path)) – Hao Oct 12 '16 at 09:48
  • In Lumen I get the following error: `There are no commands defined in the "key" namespace.` – Pathros Jan 28 '19 at 16:53
  • getting error 'There are no commands defined in the "key" namespace.' – Kamlesh Feb 12 '20 at 10:22
  • @krisanalfa Thank you very much! However, with the latest version of lumen(8.0), it will trigger Method App\Console\Commands\KeyGenerateCommand::__invoke() does not exist. To resolve this, change the function name from "fire" to "handle". This will resolve the problem. I hope this helps someone. – Jagadish Nallappa Jul 19 '21 at 16:18
32

Simply use PHP CLI. Run this from your local or a remote command line to generate a random 32-character Lumen APP_KEY:

php -r "echo bin2hex(random_bytes(16));"

Output: bae48aba23b3e4395b7f1b484dd25192

Works with PHP 7.x on Mac and Windows.

Chad Kieffer
  • 491
  • 4
  • 8
28

An easy solution is just running PHP code from the terminal (without using tinker, because that is not available with Lumen):

php -r "require 'vendor/autoload.php'; echo str_random(32).PHP_EOL;"

It uses Laravel's Str::random() function that makes use of the secure random_bytes() function.

Jeroen Noten
  • 3,574
  • 1
  • 17
  • 25
  • 5
    Oneliner with base64encoded output for Lumen >= 5.4: `php -r "require 'vendor/autoload.php'; echo base64_encode(str_random(32)).PHP_EOL;"` – 4levels Mar 20 '18 at 23:04
18

For me the easiest way to generate a Lumen key is typing on console one of these commands:

date | md5
date | md5sum

or

openssl rand -base64 24

depending of your environment. In my case, I aways use date | md5 on mac

  • Don't forget to base64 encode the md5 key for Lumen > 5.4, eg. `php -r "echo base64_encode(\"[YOUR-MD5-STRING]\");"` - add it prefixed with `base64:` in your `.env` file.. – 4levels Mar 20 '18 at 23:03
13

The APP_KEY generation is a step of development process (I don't think that creating temporarily routes is a practical way to do it). The function str_random can help us, but this function is part of Laravel/Lunmen framework. I recommend running tinker

php artisan tinker

and then run the function

>>> str_random(32)

The result is the key you're looking for.

=> "y3DLxnEczGWGN4CKUdk1S5GbMumU2dfH"

Cosmitar
  • 984
  • 12
  • 18
  • But to even get tinker to work with Lumen you need to add it. https://github.com/laravel/framework/issues/8566 – Leo Fisher Aug 31 '16 at 06:26
  • 3
    Yep, finally I found myself using `date | md5sum` on terminal and pasting the result into .env – Cosmitar Oct 03 '16 at 23:08
  • Thanks for the answer Cosmitar – Ishmael Jan 21 '19 at 20:00
  • In Lumen I get the following error: `Command "tinker" is not defined.`. But then I go to a Laravel project folder and it does work! I copied the string and then I got back to the Lumen folder. – Pathros Jan 28 '19 at 16:55
5

To generate key and use laravel command you need to install one package. The details are as below:

  1. You have to install package composer require flipbox/lumen-generator
  2. You have to add $app->register(Flipbox\LumenGenerator\LumenGeneratorServiceProvider::class); into bootstrap/app.php file.

Link: https://github.com/flipboxstudio/lumen-generator

CKE
  • 1,533
  • 19
  • 18
  • 29
Umang Soni
  • 521
  • 5
  • 9
3

All I do on mac is execute this command in the terminal:

date | md5 | pbcopy

This copies the value into the clipboard and so you can easily paste the key into the .env file.

ubuntugod
  • 592
  • 7
  • 16
2

I have used these commands:

php -r \"copy('.env.example', '.env');\"

php -r "echo password_hash(uniqid(), PASSWORD_BCRYPT).\"\n\";"

The command generates a key similar to this:

$2y$10$jb3kw/vUANyzZ4ncMa4rwuR09qldQ2OjX8PGrVB5dIlSnUAPCGjFe

1

This answer was inspired by @thomas-venturini 's update to the question. Here's a bash script that takes care of creating .env and updating it with an APP_KEY using the aforementioned PHP command and the UNIX sed command:

#!/usr/bin/env bash

function generate_app_key {
    php -r "echo md5(uniqid()).\"\n\";"
}

APP_KEY=$(generate_app_key)

sed -e s/APP_KEY=.*$/APP_KEY=${APP_KEY}/g .env.example > .env

Hope someone finds this useful.

Dawngerpony
  • 3,288
  • 2
  • 34
  • 32
1

Run php -a to start up interactive php playground.

Then run echo substr(md5(rand()), 0, 32); to generate a 32 character string.

You can then copy/paste into the .env file.

roerjo
  • 790
  • 6
  • 12
0

1.Open your terminal setup file:

vim ~/.zshrc

2.Create an alias for generating random strings:

# Lumen Key Generate
alias lumen-key="php -r \"require 'vendor/autoload.php'; echo base64_encode(str_random(32)).PHP_EOL;\""

3.Get a key whenever you need:

~/your-lumen-project via  v7.3.0
➜ lumen-key
VkxTYWZZSnhVNVEzRThXelBGZVJDVGZVYTNTcm9peHY=

You can also remove the third step by adding the key directly in .env using PHP.

Alexandre Thebaldi
  • 4,546
  • 6
  • 41
  • 55
0

[Flipbox\LumenGenerator]

Fix error: there are no comands defined...

[boostrap/app] Check if you register the Flipbox\LumenGenerator after return $app. If so move the Service provider register before return app...

/**
 * Configure extra LARAVEL commands to a lumen app
 * Check avaliable commands in git: flipboxstudio lumen-generator
 */
if($app->environment() !== 'production'){
    $app->register(Flipbox\LumenGenerator\LumenGeneratorServiceProvider::class);
}

return $app;

Lumen 8.0 / flipbox/lumen-generator 8.2

0

It Worked 100%

Simply install the flipbox/lumen-generator package

composer require flipbox/lumen-generator.

Inside your bootstrap/app.php file, add:

$app->register(Flipbox\LumenGenerator\LumenGeneratorServiceProvider::class);

Then after you can able to run php artisan commands, more info: https://github.com/flipboxstudio/lumen-generator

Najathi
  • 2,529
  • 24
  • 23
0

If you're encountering the error message "ERROR There are no commands defined in the 'key' namespace" when running the php artisan key:generate command in Lumen, it typically means that the command is not registered or available in your application.

In Lumen, the key:generate command is not included by default since Lumen doesn't come with the same set of commands as Laravel. However, generating an app key is still necessary for certain features to work correctly.

To generate an app key in Lumen, you can follow an alternative approach:

  1. Open the terminal or command prompt.

  2. Navigate to your Lumen project's root directory.

  3. Run the following command:

    php -r "echo bin2hex(random_bytes(32));"
    

    This command generates a random 32-byte string and displays it as a hexadecimal value.

  4. Copy the generated key.

  5. Open your .env file and find the line that starts with APP_KEY=. If the line doesn't exist, you can add it manually.

  6. Replace the value after APP_KEY= with the generated key you copied.

    For example:

    APP_KEY=your-generated-key
    
  7. Save the .env file.

By following these steps, you can manually generate an app key in Lumen and update it in your .env file.

Please note that while this alternative method allows you to generate an app key, it's important to ensure that the key is kept secure and not shared publicly.

stanley mbote
  • 956
  • 1
  • 7
  • 17