stats function for PHP [fwd]

Brad Fitzpatrick brad@danga.com
Wed, 24 Mar 2004 14:59:21 -0800 (PST)


PHP client maintainers:


---------- Forwarded message ----------
Date: Mon, 22 Mar 2004 14:48:53 -0800
From: Jim Young <jim@hotornot.com>
To: brad@danga.com, hotrodder@rocketmail.com

Brad, Ryan,

Hey guys. This is Jim from HOTorNOT.com. I've just started toying around
with memcached. Great work all around- it works just as advertised.

I'm using the PHP client and noticed that the stats function didn't seem to
be supported, so I whipped up
something to take care of it. Anyway, just in case it's of any use to you or
anyone else, here it is.

cheers,
jim


(new function for the MemCachedClient class)

function stats() {

    $output = array();

    if (!$this->active) {
      $this->errno = MC_ERR_NOT_ACTIVE;
      $this->errstr = "No active servers are available";

      if($this->debug)
        $this->_debug("stats(): There are no active servers available.");

      return FALSE;
    }


    foreach($this->servers as $host) {

      $sock = $this->sock_to_host($host);

      $cmd = "stats\r\n";
      $cmd_len = strlen($cmd);
      $offset = 0;

      // now send the command
      while($offset < $cmd_len) {
        $result = socket_write($sock, substr($cmd, $offset, MC_BUFFER_SZ),
MC_BUFFER_SZ);

        if($result !== FALSE)
          $offset += $result;
        elseif($offset < $cmd_len) {
          $this->errno = MC_ERR_SOCKET_WRITE;
          $this->errstr = "Failed to write to socket.";


          if($this->debug) {
            $sockerr = socket_last_error($sock);
            $this->_debug("stats(): socket_write() returned FALSE. Socket
Error $sockerr: ".socket_strerror($sockerr));
          }

          return FALSE;
        }
      }

      while ($line = socket_read($sock, MC_BUFFER_SZ, PHP_NORMAL_READ)) {
        // check for a socket_read error
        if ($line === FALSE) {
          $this->errno = MC_ERR_SOCKET_READ;
          $this->errstr = "Failed to read from socket.";

          if($this->debug) {
            $errno = socket_last_error($sock);
            $this->_debug("stats(): socket_read() returned FALSE. Error
$errno: ".socket_strerror($errno));
          }

          return FALSE;
        }
        elseif (substr($line,0,3) == 'END') {
          break;
        }
        else {
          $blah = explode(' ',$line);
          if ($blah[1]) {
            $output[$host][$blah[1]] = $blah[2];
          }
        }
      }
    }

    if ($this->debug) {
      foreach($output as $host_output) {
        foreach ($host_output as $k => $v) {
          $this->_debug("MemCache: $host => $k : $v\n");
        }
      }
    }

    return $output;
  }