How can I dump and restore the redis database on PHP, I'm using predis on my client.
Can I dump the redis database on .rdb format ?
Updated :
I dump/backup database using the following command,
$redis->bgSave();
How to restore it back to my database ?
As Malinga, Restoring happen in the restart of redis server. So you need set appendonly no. So that it will use the .rdb file.
So, I created a sample program to backup and restore redis database, Here is the code you can check
Export :
$i = 0;
$json = array();
foreach($redis->keys('*') as $key) {
$data = array();
$data['key'] = $key;
$data['ttl'] = $redis->ttl($key);
$data['value'] = bin2hex($redis->dump($key));
$json[$i] = $data;
$i++;
}
header('Content-disposition: attachment; filename=database.json');
header('Content-type: application/json');
echo json_encode($json);
Import :
if (isset($_POST['submit']) && $_POST['submit'] == 'Import') {
$types = array(
'application/json',
'application/octet-stream'
);
if (in_array($_FILES['upload']['type'], $types)) {
var_dump($_FILES);
if (move_uploaded_file($_FILES['upload']['tmp_name'], 'uploads/' . $_FILES['upload']['name']))
{
$file = file_get_contents('uploads/' . $_FILES['upload']['name'], "r");
$database = json_decode($file, true);
foreach($database as $data)
{
if ($data['ttl'] >= 0)
{
$data['ttl'] = $data['ttl'];
}
else
{
$data['ttl'] = 0;
}
if ($data['key'] && $data['value'] && !$redis->exists($data['key']))
{
$redis->restore($data['key'], $data['ttl'], hex2bin($data['value']));
}
}
}
}
}
Full code can be downloaded via GitHub