Skip to content

Instantly share code, notes, and snippets.

@galdiolo
Forked from janich/exportMysqlUsers.php
Last active May 28, 2016 00:01
Show Gist options
  • Save galdiolo/de09de274215a8f0183ebbfa6077ef04 to your computer and use it in GitHub Desktop.
Save galdiolo/de09de274215a8f0183ebbfa6077ef04 to your computer and use it in GitHub Desktop.
Export MySQL users and permissions
<?php
/**
* Export MySQL users and permissions
*
* This script exports raw CREATE USER and GRANT queries of a given database
* to help migrate MySQL users and permissions to a new server.
* Users will keep their passwords across the migration.
*
* Warning: The import queries expects exactly the same database structure!
*
* This was made in 10 min a rainy afternoon.
* Usage is on your own responsibility!
* Feel free to improve it.
*
* @requires PHP 5.3+
* @package ExportMySQLUsers
* @author Janich Rasmussen <janich@gmail.com>
* @license http://www.dbad-license.org/ DBAD license
*/
// Set up database root credentials
$host = 'localhost';
$user = 'root';
$pass = '--Insert Your Root Password Here And Delete It When You Are Done--';
$port = 3306;
// ---- Do not edit below this ----
// Misc settings
header('Content-type: text/plain; Charset=UTF-8');
// Final import queries goes here
$export = array();
// Connect to database
$link = new mysqli($host, $user, $pass, 'mysql', $port);
// Test connection
if ($link->connect_error)
{
printf('Connect failed (%s): %s', $link->connect_errno, $link->connect_error);
die();
}
// Do this right!
$link->query('SET NAMES \'utf8\'');
// Get users from database
$result = $link->query('SELECT `User`, `Host`, `Password` FROM `user`');
if ($result)
{
while ($row = $result->fetch_row())
{
$user = $row[0];
$host = $row[1];
$pass = $row[2];
$export[] = 'CREATE USER \''. $user .'\'@\''. $host .'\' IDENTIFIED BY \''. $pass .'\'';
// Fetch any permissions found in database
$result2 = $link->query('SHOW GRANTS FOR `'. $user .'`@`'. $host .'`');
if ($result2)
{
while ($row2 = $result2->fetch_row())
{
$export[] = $row2[0];
}
}
}
}
$link->close();
echo implode(";\n", $export);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment