Skip to content

Instantly share code, notes, and snippets.

@colinmollenhour
Created March 11, 2012 18:38
Show Gist options
  • Save colinmollenhour/2017622 to your computer and use it in GitHub Desktop.
Save colinmollenhour/2017622 to your computer and use it in GitHub Desktop.
Super-lightweight Redis client
<?php
/**
* Super-lightweight Redis client
*
* @param resource $sock
* @param string $cmd
* @return bool|int|string
*/
function redis_cmd($sock, $cmd)
{
$args = explode(' ', $cmd);
foreach($args as $i => $arg) {
$args[$i] = sprintf("$%d\r\n%s", strlen($arg), $arg);
}
$cmd = sprintf("*%d\r\n%s\r\n",count($args), implode("\r\n", $args));
if( ! fwrite($sock, $cmd)) {
return FALSE;
}
$reply = fgets($sock);
if($reply === FALSE) {
return FALSE;
}
$reply = rtrim($reply, "\r\n");
$replyType = substr($reply, 0, 1);
switch ($replyType) {
case '-':
case '*': // Not supported
return FALSE;
case ':':
return intval(substr($reply, 1));
case '+':
return substr($reply, 1);
case '$':
if ($reply == '$-1') return FALSE;
$size = (int) substr($reply, 1);
$response = stream_get_contents($sock, $size + 2);
if( ! $response)
return FALSE;
return substr($response, 0, $size);
default:
return FALSE;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment