75 lines
2.2 KiB
PHP
75 lines
2.2 KiB
PHP
<?php
|
|
// Usage: place this script next to users.txt and run: php import_users.php
|
|
// It will create users_with_passwords.txt with "login:password" lines.
|
|
|
|
require_once __DIR__ . '/config/db.php';
|
|
|
|
$inputFile = __DIR__ . '/users.txt';
|
|
$outputFile = __DIR__ . '/users_with_passwords.txt';
|
|
|
|
if (!file_exists($inputFile)) {
|
|
fwrite(STDERR, "Input file not found: {$inputFile}\n");
|
|
exit(1);
|
|
}
|
|
|
|
$lines = file($inputFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
|
|
if ($lines === false) {
|
|
fwrite(STDERR, "Failed to read input file.\n");
|
|
exit(1);
|
|
}
|
|
|
|
$charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
|
|
$charsetLen = strlen($charset);
|
|
|
|
function generatePassword(string $charset, int $charsetLen, int $length = 6): string
|
|
{
|
|
$password = '';
|
|
for ($i = 0; $i < $length; $i++) {
|
|
$password .= $charset[random_int(0, $charsetLen - 1)];
|
|
}
|
|
return $password;
|
|
}
|
|
|
|
$pdo->beginTransaction();
|
|
try {
|
|
$selectStmt = $pdo->prepare("SELECT id FROM users WHERE username = ?");
|
|
$insertStmt = $pdo->prepare("INSERT INTO users (username, password_hash) VALUES (?, ?)");
|
|
$updateStmt = $pdo->prepare("UPDATE users SET password_hash = ? WHERE id = ?");
|
|
|
|
$out = fopen($outputFile, 'w');
|
|
if ($out === false) {
|
|
throw new RuntimeException('Failed to open output file for writing.');
|
|
}
|
|
|
|
$seen = [];
|
|
foreach ($lines as $line) {
|
|
$username = trim($line);
|
|
if ($username === '' || isset($seen[$username])) {
|
|
continue;
|
|
}
|
|
$seen[$username] = true;
|
|
|
|
$password = generatePassword($charset, $charsetLen, 6);
|
|
$hash = password_hash($password, PASSWORD_BCRYPT);
|
|
|
|
$selectStmt->execute([$username]);
|
|
$user = $selectStmt->fetch(PDO::FETCH_ASSOC);
|
|
if ($user) {
|
|
$updateStmt->execute([$hash, $user['id']]);
|
|
} else {
|
|
$insertStmt->execute([$username, $hash]);
|
|
}
|
|
|
|
fwrite($out, $username . ':' . $password . PHP_EOL);
|
|
}
|
|
|
|
fclose($out);
|
|
$pdo->commit();
|
|
echo "Done. Output: {$outputFile}\n";
|
|
} catch (Throwable $e) {
|
|
$pdo->rollBack();
|
|
fwrite(STDERR, "Error: " . $e->getMessage() . "\n");
|
|
exit(1);
|
|
}
|
|
?>
|