lumen 5.6 设置APP_KEY为32位长的随机字符串

2018-06-19  本文已影响0人  ling_1992

在 App\Console\Commands下 添加以下内容的KeyGenerateCommand.php文件

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class KeyGenerateCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'key:generate';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Set the application key';

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function handle()
    {
        $key = $this->generateRandomKey();

        file_put_contents(base_path('.env'), preg_replace(
            '/^APP_KEY=[\w]*/m',
            'APP_KEY='.$key,
            file_get_contents(base_path('.env'))
        ));

        $this->info("Application key [$key] set successfully.");
    }

    /**
     * Generate a random key for the application.
     *
     * @return string
     */
    protected function generateRandomKey()
    {
        return str_random(32);
    }

}

将指令注入
修改App\Console 下的Kernel.php 文件

 protected $commands = [
        //注入指令
        'App\Console\Commands\KeyGenerateCommand', 
    ];

现在可以使用 php artisan key:generate 指令 修改 .env中的APP_KEY 的值

上一篇下一篇

猜你喜欢

热点阅读