Skip to content

Instantly share code, notes, and snippets.

@tastycode
Created July 6, 2011 22:31
Show Gist options
  • Save tastycode/1068507 to your computer and use it in GitHub Desktop.
Save tastycode/1068507 to your computer and use it in GitHub Desktop.
PHP Memcached Server
<?php
/**
* A really simple memcache implementation for PHP - Based on https://gist.github.com/949850
* Run the script, it listens on port 8000
* To store a value, http://localhost:8000/write/family/key/val
* To read a value , http://localhost:8000/read/family/key
*
* This is just a proof of concept .. it doesn't handle errors etc..
*
* Thomas Devol
*/
class SimpleCache {
var $cache;
function __construct() {
$cache=array();
}
function get($family, $key) {
if (!isset($this->cache[$family]))
$this->cache[$family]=array();
return $this->cache[$family][$key];
}
function set($family,$key,$value) {
if (!isset($this->cache[$family]))
$this->cache[$family]=array();
$this->cache[$family][$key]=$value;
}
}
$cache = new SimpleCache();
$app = function($request,&$cache) {
$matches=array();
preg_match("/(GET|POST|PUT|DELETE) (\/.*) HTTP\/1.1/",$request,$matches);
$proto = $matches[1];
$path = $matches[2];
$parts = split("/",$path);
$action = $parts[1];
$family = $parts[2];
$key = $parts[3];
$value = $parts[4];
$body="" ;
if ($action == 'read') {
$body=$cache->get($family,$key);
} elseif ($action == 'write') {
$cache->set($family,$key,$value);
}
return array(
'200 OK',
array('Content-Type' => 'text/html;charset=utf-8'),
$body
);
};
$socket = stream_socket_server('tcp://0.0.0.0:8000', $errno, $errstr);
if (!$socket) {
echo $errstr, ' (', $errno,')', PHP_EOL;
} else {
$defaults = array(
'Content-Type' => 'text/html',
'Server' => 'PHP '.phpversion()
);
echo 'Server is running on 0.0.0.0:8000, relax.', PHP_EOL;
while ($conn = stream_socket_accept($socket, -1)) {
$request = '';
while (substr($request, -4) !== "\r\n\r\n") {
$request .= fread($conn, 1024);
}
list($code, $headers, $body) = $app($request,$cache);
$headers += $defaults;
if (!isset($headers['Content-Length'])) {
$headers['Content-Length'] = strlen($body);
}
$header = '';
foreach ($headers as $k => $v) {
$header .= $k.': '.$v."\r\n";
}
fwrite($conn, implode("\r\n", array(
'HTTP/1.1 '.$code,
$header,
$body
)));
fclose($conn);
}
fclose($socket);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment