Skip to content

Instantly share code, notes, and snippets.

@nawawishkid-old
Created April 7, 2018 15:17
Show Gist options
  • Save nawawishkid-old/e40e3ec7fc10a9e1c0a059a48a3a9e3f to your computer and use it in GitHub Desktop.
Save nawawishkid-old/e40e3ec7fc10a9e1c0a059a48a3a9e3f to your computer and use it in GitHub Desktop.
Try using PHPRedis to manipulate Redis database.
<?php
$redis = new Redis();
$redis->connect( '127.0.0.1', 6379 );
legible( "Connection to redis server successfully." );
$redis->auth( 'redis181409943' );
legible( "Client authenticated!" );
legible( "Server is running: " . $redis->ping() );
// Normal string
$redis->set( 'key-string', 'This is string.' );
$redis->expire( 'key-string', 120 );
status( 'key-string' );
// List of string
$redis->rPush( 'key-list', 'list item 1' );
$redis->rPush( 'key-list', 'list item 2' );
$redis->rPush( 'key-list', 'list item 3' );
$redis->rPush( 'key-list', 'list item 4' );
$redis->expire( 'key-list', 120 );
status( 'key-list' );
// Set
$redis->sAdd( 'key-set', 'set item 1' );
$redis->sAdd( 'key-set', 'set item 2' );
$redis->sAdd( 'key-set', 'set item 3' );
$redis->sAdd( 'key-set', 'set item 4' );
$redis->sAdd( 'key-set', 'set item 3' );
$redis->expire( 'key-set', 120 );
status( 'key-set' );
// Sorted set
$redis->zAdd( 'key-zset', 100, 'set item 1' );
$redis->zAdd( 'key-zset', 30, 'set item 2' );
$redis->zAdd( 'key-zset', 70, 'set item 3' );
$redis->zAdd( 'key-zset', 10, 'set item 4' );
$redis->zAdd( 'key-zset', 50, 'set item 3' );
$redis->expire( 'key-zset', 120 );
status( 'key-zset' );
// Hash
$redis->hMSet( 'key-hash', [
'username' => 'nawawishkid',
'email' => '[email protected]',
'password' => 'passwordnaja',
]);
$redis->expire( 'key-hash', 120 );
status( 'key-hash' );
// $redis->del( 'key-string' );
// $redis->del( 'key-list' );
// $redis->del( 'key-set' );
// $redis->del( 'key-zset' );
// $redis->del( 'key-hash' );
/**
* Display functions
*/
function status( $key ) {
global $redis;
$typeInt = $redis->type( $key );
$value = null;
$type = null;
switch ( $typeInt ) {
case 1:
$value = "'" . $redis->get( $key ) . "'";
$type = "string";
break;
case 3:
$value = $redis->lRange( $key, 0, -1 );
$type = "list";
break;
case 2:
$value = $redis->sMembers( $key );
$type = "set";
break;
case 4:
$value = $redis->zRange( $key, 0, -1 );
$type = "sorted set";
break;
case 5:
$value = $redis->hGetAll( $key );
$type = "hash";
break;
default:
$value = "Error: no value.";
$type = "Error: invalid data type.";
break;
}
legible( "Set `$key`" );
legible( "Type of `$key` is " . $type );
legible( "The value is:" );
legible( $value );
legible( "`$key` will expire in " . $redis->ttl( $key ) . " seconds." );
}
function legible( $data, $is_dump = false ) {
if ( ! is_array( $data ) ) {
echo $data . "<br>\n";
return;
}
echo "<pre>";
$is_dump ? var_dump( $data ) : print_r( $data );
echo "</pre><br>\n";
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment