phpsymfony

Symfony - Terminal Command to generate a new APP_SECRET


I writing a public Symfony app. So I need to expose it on Packagist. How can I run a post-install-cmd to automatically set a new random APP_SECRET?

This would be nice to know and I think it's important. I did not found anything about that in the internet.


Solution

  • You can use the symfony/console,

    Create for example:

    php bin/console make:command regenerate-app-secret
    

    in src/Command/RegenerateAppSecretCommand.php

    <?php
    
    namespace App\Command;
    
    use Symfony\Component\Console\Command\Command;
    use Symfony\Component\Console\Input\InputArgument;
    use Symfony\Component\Console\Input\InputInterface;
    use Symfony\Component\Console\Input\InputOption;
    use Symfony\Component\Console\Output\OutputInterface;
    use Symfony\Component\Console\Style\SymfonyStyle;
    
    class RegenerateAppSecretCommand extends Command
    {
        protected static $defaultName = 'regenerate-app-secret';
    
        protected function execute(InputInterface $input, OutputInterface $output): int
        {
            $io = new SymfonyStyle($input, $output);
    
            $a = '0123456789abcdef';
            $secret = '';
            for ($i = 0; $i < 32; $i++) {
                $secret .= $a[rand(0, 15)];
            }
    
            $r = shell_exec('sed -i -E "s/^APP_SECRET=.{32}$/APP_SECRET=' . $secret . '/" .env');
    
            $io->success('New APP_SECRET was generated: ' . $secret);
    
            return 0;
        }
    }
    

    Run:

    php bin/console regenerate-app-secret