Redis BackUp and Restore On PHP

Redis is an open source (BSD licensed), in-memory data structure store, used as database, cache and message broker. Redis also referred as key-value in memory data store typically used for caches and other such mechanisms to speed up web applications. RDB persistence performs point-in-time snapshots of your dataset at specified intervals. RDB files are perfect for backups. For instance you may want to archive your RDB files every hour for the latest 24 hours, and to save an RDB snapshot every day for 30 days. This allows you to easily restore different versions of the data set in case of disasters.

RDB is not good if you need to minimize the chance of data loss in case Redis stops working (for example after a power outage). You can configure different save points where an RDB is produced (for instance after at least five minutes and 100 writes against the data set, but you can have multiple save points). However you’ll usually create an RDB snapshot every five minutes or more, so in case of Redis stopping working without a correct shutdown for any reason you should be prepared to lose the latest minutes of data.

Backup program is written in the manner to get the key and value from the database and then the value is stored in JSON as hexadecimal format on our sample code, we can also store the value as plain data. Here we used foreach to save all data in JSON format.

$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;
header('Content-disposition: attachment; filename=database.json');
header('Content-type: application/json');
echo json_encode($json);

Restore is done by inserting the value to database from JSON file. Here is the sample code for restoring the database,

$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']));

You can download the source code via GitHub. Downloaded source code can be run/executed.
Please leave your valuable comments/suggestions/feedback on below comment box if any.

Thank You !!


SIVA SANKAR, Working as a Software Engineer, Blogging is my hobby. I completed my Bachelors of Engineering (Computer Science Engineering) in Chennai, India. and my Master of Engineering (Embedded System Technologies) in Tamilnadu, India.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.