__DIR__ . '/../.env', 'lgp-api/.env' => __DIR__ . '/../../lgp-api/.env', 'lgp-wx-api/.env' => '/www/sites/lgp-wx-api/index/lgp-wx-api/.env', ]; function readEnv(string $path): array { if (!is_file($path)) { return []; } $values = []; foreach (file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) as $line) { $line = trim($line); if ($line === '' || str_starts_with($line, '#') || !str_contains($line, '=')) { continue; } [$key, $value] = explode('=', $line, 2); $values[trim($key)] = trim(trim($value), "\"'"); } return $values; } $target = $argv[1] ?? null; // 环境重建后 host 也可能变了,所以每套凭据都对「自带 host」和「当前 mysql 容器」各试一次 $hosts = ['mysql8']; foreach ($candidates as $label => $path) { $env = readEnv($path); if (empty($env)) { echo str_pad($label, 32) . " 文件不存在\n"; continue; } $envHost = $env['DB_HOST'] ?? '127.0.0.1'; foreach (array_unique([$envHost, ...$hosts]) as $host) { $port = $env['DB_PORT'] ?? '3306'; $db = $target ?: ($env['DB_DATABASE'] ?? ''); $user = $env['DB_USERNAME'] ?? 'root'; try { $pdo = new PDO( "mysql:host={$host};port={$port};dbname={$db};charset=utf8mb4", $user, $env['DB_PASSWORD'] ?? '', [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_TIMEOUT => 5] ); $count = $pdo->query('SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = DATABASE()')->fetchColumn(); echo str_pad($label, 32) . " 可连接 host={$host} db={$db} 表数={$count}\n"; } catch (Throwable $e) { $reason = preg_replace('/using password: (YES|NO)/', 'using password: ***', $e->getMessage()); echo str_pad($label, 32) . " 连不上 host={$host} " . $reason . "\n"; } } }