Skip to content

Instantly share code, notes, and snippets.

@littlefuntik
Last active March 14, 2023 23:47
Show Gist options
  • Save littlefuntik/b3effc87fe08dd46c5bffbc0e1be8fd2 to your computer and use it in GitHub Desktop.
Save littlefuntik/b3effc87fe08dd46c5bffbc0e1be8fd2 to your computer and use it in GitHub Desktop.
FLUSH DB Redis simple PHP (stream socket client)
<?php
// config
$redis_host = getenv('REDIS_HOST') ?: '127.0.0.1';
$redis_port = getenv('REDIS_PORT') ?: '6379';
$redis_db = getenv('REDIS_DB_NAME') ?: '0';
// init
$redis_server = sprintf('%s:%d', $redis_host, $redis_port);
$redis_create_request = function ($args) {
$cmd = '*' . count($args) . "\r\n";
foreach ($args as $item) {
$cmd .= '$' . strlen($item) . "\r\n" . $item . "\r\n";
}
return $cmd;
};
// connect to the Redis
$socket = stream_socket_client($redis_server);
// run command
fwrite($socket, $redis_create_request(['SELECT', $redis_db]));
fwrite($socket, $redis_create_request(['FLUSHDB']));
$cmd_result = fgets($socket);
fwrite('-' === substr($cmd_result, 0, 1) ? STDERR : STDOUT, $cmd_result . "\n");
// close connection to the Redis
fclose($socket);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment