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

示例代码

<?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;
}