# HG changeset patch # User Dan # Date 1220302203 14400 # Node ID 2634d550a97bdc99e2ca3200f05333bf7b62a8fe # Parent 774751e7faed6327110c906adb9069d4923edc96 Added full cookie support to webserver diff -r 774751e7faed -r 2634d550a97b webserver.php --- a/webserver.php Mon Sep 01 16:48:47 2008 -0400 +++ b/webserver.php Mon Sep 01 16:50:03 2008 -0400 @@ -18,7 +18,7 @@ * @const string */ -define('HTTPD_VERSION', '0.1b4'); +define('HTTPD_VERSION', '0.1b5'); /** * Length of keep-alive connections @@ -467,6 +467,11 @@ $uri =& $match[2]; // set client headers + foreach ( $_SERVER as $key => $_ ) + { + if ( preg_match('/^HTTP_/', $key) ) + unset($_SERVER[$key]); + } unset($client_headers[0]); foreach ( $client_headers as $line ) { @@ -482,11 +487,19 @@ $this->in_keepalive = ( strtolower($_SERVER['HTTP_CONNECTION']) === 'keep-alive' ); } - // parse authorization, if any - if ( isset($_SERVER['PHP_AUTH_USER']) ) + // process cookies + $_COOKIE = array(); + if ( isset($_SERVER['HTTP_COOKIE']) ) { - unset($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']); + preg_match_all('/([a-z0-9_-]+)=([^;]*)(?:;|$)/', trim($_SERVER['HTTP_COOKIE']), $matches); + foreach ( $matches[0] as $i => $match ) + { + $_COOKIE[$matches[1][$i]] = str_replace('\\r', "\r", str_replace('\\n', "\n", str_replace(rawurlencode(';'), ';', $matches[2][$i]))); + } } + + // parse authorization, if any + unset($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']); if ( isset($_SERVER['HTTP_AUTHORIZATION']) ) { $data = $_SERVER['HTTP_AUTHORIZATION']; @@ -1196,6 +1209,43 @@ } /** + * Sets a cookie. Identical to PHP's setcookie() function. + * @param string Cookie name + * @param string Cookie value + * @param int Expiration time of cookie as a UNIX timestamp; if omitted or set to zero, cookie will expire at the end of the user's browser session + * @param string Path of the cookie + * @param string Domain the cookie is available under + * @param bool If true, browser will only send the cookie through an HTTPS connection. + * @param bool If true, cookie will not be accessible to client-side code + */ + + function setcookie($cookiename, $cookievalue, $expiry = false, $path = false, $domain = false, $secure = false, $httponly = false) + { + $header = "Set-Cookie: $cookiename=$cookievalue"; + if ( !empty($expiry) ) + $header .= "; expires=" . date('D, d-M-Y H:i:s T', $expiry); + if ( !empty($path) ) + $header .= "; path=$path"; + if ( !empty($domain) ) + $header .= "; domain=$domain"; + if ( $secure ) + $header .= "; secure"; + if ( $httponly ) + $header .= "; httponly"; + + if ( is_int($expiry) && $expiry < time() ) + { + unset($_COOKIE[$cookiename]); + } + else + { + $_COOKIE[$cookiename] = $cookievalue; + } + + $this->header($header); + } + + /** * Sends the client an HTTP error page * @param resource Socket connection to client * @param int HTTP status code