• 支持Win/Linux/Mac等环境
  • 支持交互输入
  • 支持错误重试

示例代码

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
<?php

/**
 * 创建管理员账号脚本
 */

require_once dirname(__DIR__) . '/UpforPHP/bootstrap.php';
require_once dirname(__DIR__) . '/vendor/autoload.php';

use Upfor\UpforPHP\Library\Password;

if (PHP_SAPI != 'cli') {
    echo '请在CLI模式下运行';
    die;
}

// 生成密码
if (isset($argv[1])) {
    echo '密  码:', $argv[1], "\n";
    echo '加密后:', "\n", Password::hash($argv[1]), "\n";
    die;
}

// 创建账号

$email = '';
$password = '';
$realName = '';
$mobile = '';

echo '创建管理员账户...', "\n\n";

// 邮箱
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo '请输入[email]:';
    READ_EMAIL:
    echo "\n";
    $email = read();
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo '[email]格式不正确, 请重新输入:';
        goto READ_EMAIL;
    }
    echo "\n";
}

if (db()->table('admin_user')->where('email', $email)->has()) {
    echo '账号已存在!!!', "\n";
    die;
}

// 密码
if (strlen($password) < 6) {
    echo '请输入[password]:';
    READ_PASSWORD:
    echo "\n";
    $password = read();

    if (strlen($password) < 6) {
        echo '[password]长度不可小于6位, 请重新输入:';
        goto READ_PASSWORD;
    }
    echo "\n";
}

// 姓名
if (strlen($realName) < 6) {
    echo '请输入[姓名]:';
    READ_REAL_NAME:
    echo "\n";
    $realName = read();

    if (strlen($realName) < 2) {
        echo '[姓名]错误, 请重新输入:';
        goto READ_REAL_NAME;
    }
    echo "\n";
}

// 手机
if (strlen($mobile) < 6) {
    echo '请输入[mobile]:';
    READ_MOBILE:
    echo "\n";
    $mobile = read();

    if (strlen($mobile) != 11 || !is_numeric($mobile)) {
        echo '[mobile]错误, 请重新输入:';
        goto READ_MOBILE;
    }
    echo "\n";
}

$data = [
    'email' => $email,
    'password' => Password::hash($password),
    'real_name' => $realName,
    'mobile' => $mobile,
    'status' => 1,
    'last_login_ip' => '0',
    'last_login_time' => '0',
    'create_time' => time(),
    'update_time' => time(),
];

if (!model('AdminUser')->insert($data)) {
    $error = db()->errorInfo();
    echo '创建账号失败, 请重试';
    var_dump($error);
    die;
}

echo '管理员账号创建成功!!!', "\n";
var_dump($data);
die;

// 交互式读取CLI输入
function read() {
    $fp = fopen('php://stdin', 'r');
    $input = fgets($fp, 255);
    fclose($fp);
    $input = trim($input);

    return $input;
}