\seekquarry\yioop\libraryWebSite

A single file, low dependency, pure PHP web server and web routing engine class.

This software can be used to route requests, and hence, serve as a micro framework for use under a traditional web server such as Apache, nginx, or lighttpd. It can also be used to serve web apps as a stand alone web server for apps created using its routing facility. As a standalone web server, it is web request event-driven, supporting asynchronous I/O for web traffic. It also supports timers for background events. Unlike similar PHP software, as a Web Server it instantiates traditional PHP superglobals like $_GET, $_POST, $_REQUEST, $_COOKIE, $_SESSION, $_FILES, etc and endeavors to make it easy to code apps in a rapid PHP style.

Summary

Methods
Properties
Constants
__construct()
isCli()
__call()
subsite()
addRoute()
middleware()
process()
trigger()
header()
setCookie()
sessionStart()
fileGetContents()
filePutContents()
clearFileCache()
moveUploadedFile()
setTimer()
clearTimer()
listen()
processInternalRequest()
mimeType()
$immortal_stream_keys
$base_path
CONNECTION
DATA
MODIFIED_TIME
CONTEXT
REQUEST_HEAD
LEN_LONGEST_HTTP_METHOD
getResponseData()
checkMatch()
processTimers()
processRequestStreams()
processServerRequest()
initRequestStream()
processResponseStreams()
parseRequest()
setGlobals()
defaultErrorHandler()
initializeBadRequestResponse()
cullDeadStreams()
shutdownHttpStream()
shutdownHttpWriteStream()
$default_server_globals
$routes
$session_configs
$in_streams
$out_streams
$middle_wares
$request_script
$sessions
$session_queue
$timers
$timer_alarms
$current_session
$http_methods
$header_data
$content_type
$file_cache
$is_cli
$is_secure
N/A
No private methods found
No private properties found
N/A

Constants

CONNECTION

CONNECTION

DATA

DATA

MODIFIED_TIME

MODIFIED_TIME

CONTEXT

CONTEXT

REQUEST_HEAD

REQUEST_HEAD

LEN_LONGEST_HTTP_METHOD

LEN_LONGEST_HTTP_METHOD

Properties

$immortal_stream_keys

$immortal_stream_keys : array

Keys of stream that won't disappear (for example the server socket)

Type

array

$base_path

$base_path : string

Used to determine portion of path to ignore when checking if a route matches against the current request.

Type

string

$default_server_globals

$default_server_globals : array

Default values to write into $_SERVER before processing a connection request (in CLI mode)

Type

array

$routes

$routes : array

Associative array http_method => array of how to handle paths for that method

Type

array

$session_configs

$session_configs : array

Default values used to set up session variables

Type

array

$in_streams

$in_streams : array

Array of all connection streams for which we are receiving data from client together with associated stream info

Type

array

$out_streams

$out_streams : array

Array of all connection streams for which we are writing data to a client together with associated stream info

Type

array

$middle_wares

$middle_wares : array

Middle ware callbacks to run when processing a request

Type

array

$request_script

$request_script : array

Filename of currently requested script

Type

array

$sessions

$sessions : array

Used to store session data in ram for all currently active sessions

Type

array

$session_queue

$session_queue : array

Keeps an ordering of currently actively sessions so if run out of memory know who to evict

Type

array

$timers

$timers : array

Timer function callbacks that have been declared

Type

array

$timer_alarms

$timer_alarms : \SplMinHeap

Priority queue of which timers are about to go off

Type

\SplMinHeap

$current_session

$current_session : string

Cookie name value of the currently active request's session

Type

string

$http_methods

$http_methods : array

List of HTTP methods for which routes have been declared

Type

array

$header_data

$header_data : string

Holds the header portion so far of the HTTP response

Type

string

$content_type

$content_type : boolean

Whether the current response already has declared a Content-Type.

If not, WebSite will default to adding a text/html header

Type

boolean

$file_cache

$file_cache : array

Used to cache in RAM files which have been read or written by the fileGetContents or filePutContents

Type

array

$is_cli

$is_cli : boolean

Whether this object is being run from teh command line with a listen() call or if it is being run under a web server and so only used for routing

Type

boolean

$is_secure

$is_secure : boolean

Whether https is being used

Type

boolean

Methods

__construct()

__construct(string  $base_path = "") 

Sets the base path used for determining request routes. Sets precision for timed events and sets up timer heap and other field variables

Parameters

string $base_path

used to determine portion of path to ignore when checking if a route matches against the current request. If it is left blank, then a base path will be computed using the $_SERVER script name variable.

isCli()

isCli() : boolean

Returns whether this class is being used from the command-line or in a web server/cgi setting

Returns

boolean —

whther the class is being run from the command line

__call()

__call(string  $method, array  $route_callback) 

Magic method __call is called whenever an unknown method is called for this class. In this case, we check if the method name corresponds to a lower case HTTP command. In which case, we check that the arguments are a two element array with a route and a callback function and add the appropriate route to a routing table.

Parameters

string $method

HTTP command to add $route_callack for in routing table

array $route_callback

a two element array consisting of a routing pattern and a callback function. In the route pattern

  • acts as a wildcare. {var_name} in a path can be used to set up a $_GET field for the match. Example $routes: /foo match requests to /foo /foo*goo matches against paths like /foogoo /foodgoo /footsygoo /thread/{thread_num} would match /thread/5 and would set up a variable $_GET['thread_num'] = 5 as well as $_REQUEST['thread_num'] = 5 The second element of the $route_callback should be a callable function to be called in the event that the route pattern is matched

subsite()

subsite(string  $route, \seekquarry\yioop\library\WebSite  $subsite) 

Used to add all the routes and callbacks of a WebSite object to the current WebSite object under paths matching $route.

Parameters

string $route

request pattern to match

\seekquarry\yioop\library\WebSite $subsite

WebSite object to add sub routes from

addRoute()

addRoute(string  $method, string  $route, callable  $callback) 

Generic function for associating a function $callback to be called when a web request using $method method and with a uri matching $route occurs.

Parameters

string $method

the name of a web request method for example, "GET"

string $route

request pattern to match

callable $callback

function to be called if the incoming request matches with $method and $route

middleware()

middleware(callable  $callback) 

Adds a middle ware callback that should be called before any processing on the request is done.

Parameters

callable $callback

function to be called before processing of request

process()

process() 

Cause all the current HTTP request to be processed according to the middleware callbacks and routes currently set on this WebSite object.

trigger()

trigger(string  $method, string  $route) : boolean

Calls any callbacks associated with a given $method and $route provided that recursion in method route call is not detected.

Parameters

string $method

the name of a web request method for example, "GET"

string $route

request pattern to match

Returns

boolean —

whether the $route was handled by any callback

header()

header(string  $header) 

Adds a new HTTP header to the list of header that will be sent with HTTP response. If the value of $header begins with HTTP/ then it is assumed that $header is the response message not a header. In this case, the value of $header will become the response message, replacing any existing messages if present. This function defaults to PHP's built-in header() function when this script is run from a non-CLI context.

Parameters

string $header

HTTP header or message to send with HTTP response

setCookie()

setCookie(string  $name, string  $value = "", integer  $expire, string  $path = "", string  $domain = "", string  $secure = false, boolean  $httponly = false) 

Sends an HTTP cookie header as part of the HTTP response. If this method is run from a non-CLI context then this function defaults to PHP's built-in function setcookie();

Cookies returned from a parituclar client will appear in the $_COOKIE superglobal.

Parameters

string $name

name of cookie

string $value

value associated with cookie

integer $expire

Unix timestamp for when the cookie expires

string $path

request path associated with the cookie

string $domain

request domain associated with the cookie

string $secure

whether the cookie should only be sent if HTTPS in use

boolean $httponly

whether or not the cookie is available only over HTTP, and not available to client-side Javascript

sessionStart()

sessionStart(array  $options = array()) 

Starts a web session. This involves sending a HTTP cookie header with a unique value to identify the client. When this client returns the cookie, session data is looked up. When run in CLI mode session data is stored in RAM. When run under a different web server, this method defaults to PHP's built-in function session_start().

Parameters

array $options

field that can be set are mainly related to the session cookie: 'name' (for cookie name), 'cookie_path', 'cookie_lifetime' (in seconds from now), 'cookie_domain', 'cookie_secure', 'cookie_httponly'

fileGetContents()

fileGetContents(string  $filename, boolean  $force_read = false) : string

Reads in the file $filename and returns its contents as a string.

In non-CLI mode this method maps directly to PHP's built-in function file_get_contents(). In CLI mode, it checks if the file exists in its Marker Algorithm based RAM cache (Fiat et al 1991). If so, it directly returns it. Otherwise, it reads it in using blocking I/O file_get_contents() and caches it before return its string contents. Note this function assumes that only the web server is performing I/O with this file. filemtime() can be used to see if a file on disk has been changed and then you can use $force_read = true below to force re- reading the file into the cache

Parameters

string $filename

name of file to get contents of

boolean $force_read

whether to force the file to be read from presistent storage rather than the cache

Returns

string —

contents of the file given by $filename

filePutContents()

filePutContents(string  $filename, string  $data) : integer

Writes $data to the persistent file with name $filename. Saves a copy in the RAM cache if there is a copy already there.

Parameters

string $filename

name of file to write to persistent storages

string $data

string of data to store in file

Returns

integer —

number of bytes written

clearFileCache()

clearFileCache() 

Deletes the files stored in the RAM FileCache

moveUploadedFile()

moveUploadedFile(string  $filename, string  $destination) 

Used to move a file that was uploaded from a form on the client to the desired location on the server. In non-CLI mode this calls PHP's built-in move_uploaded_file() function

Parameters

string $filename

tmp_name in $_FILES of the uploaded file

string $destination

where on server the file should be moved to

setTimer()

setTimer(float  $time, callable  $callback, boolean  $repeating = true) : integer

Sets up a repeating or one-time timer that calls $callback every or after $time seconds

Parameters

float $time

time in seconds (fractional seconds okay) after which $callback should be called. Or interval between calls if this is a repeating timer.

callable $callback

a function to be called after now + $time

boolean $repeating

whether $callback should be called every $time seconds or just once.

Returns

integer —

an id for the timer that can be used to turn it off (@see clearTimer())

clearTimer()

clearTimer(integer  $timer_id) 

Deletes a timer for the list of active timers. (@see setTimer)

Parameters

integer $timer_id

the id of the timer to remove

listen()

listen(integer  $address, mixed  $config_array_or_ini_filename = false) 

Starts an Atto Web Server listening at $address using the configuration values provided. It also has this server's event loop. As web requests come in $this->process is called to handle them. This input and output tcp streams used by this method are non-blocking. Detecting traffic is done using stream_select(). This maps to Unix-select calls, which seemed to be the most cross-platform compatible way to do things.

Streaming methods could be easily re-written to support libevent (doesn't work yet PHP7) or more modern event library

Parameters

integer $address

address and port to listen for web requests on

mixed $config_array_or_ini_filename

either an associative array of configuration parameters or the filename of a .ini with such parameters. Things that can be set are mainly fields that might typically show up in the $_SERVER superglobal. See the $default_server_globals variable below for some of them. The SERVER_CONTENT field can be set to an array of stream context field values and these can be used to configure the server to handle SSL/TLS (one of the examples in the examples folder.)

processInternalRequest()

processInternalRequest(string  $url, boolean  $include_headers = false, array  $post_data = null) : string

Used to handle local web page/HTTP requests made from a running WebSite script back to itself. For example, if while processing a Website ROUTE, one wanted to do curl request for another local page.

Since WebSite is is single-threaded, such a request would block until the current page was done processing, but as the current page depends on the blocked request, this would cause a deadlock. To avoid this WebSite's should check if a request is local, and if so, call processInternalRequest in lieu of making a real web request, using curl, sockets, etc.

Parameters

string $url

local page url requested

boolean $include_headers

whether to include HTTP response headers in the returned results as if it had be a real web request

array $post_data

variables (if any) to be used in an internal HTTP POST request.

Returns

string —

web page that WebSite would have reqsponded with if the request had been made as a usual web request.

mimeType()

mimeType(string  $file_name, boolean  $use_extension = false) : string

Returns the mime type of the provided file name if it can be determined.

(This function is from the seekquarry/yioop project)

Parameters

string $file_name

(name of file including path to figure out mime type for)

boolean $use_extension

whether to just try to guess from the file extension rather than looking at the file

Returns

string —

mime type or unknown if can't be determined

getResponseData()

getResponseData(boolean  $include_headers = true) : string

Used by usual and internal requests to compute response string of the web server to the web client's request. In the case of internal requests, it is sometimes usesful to return just the body of the response without HTTP headers

Parameters

boolean $include_headers

whether to include HTTP headers at beginning of reponse

Returns

string —

HTTP response to web client request

checkMatch()

checkMatch(string  $request_path, string  $route) : boolean

Checks if a portion of a request uri path matches a Atto server route.

Parameters

string $request_path

part of a path portion of a request uri

string $route

a route that might be handled by Atto Server

Returns

boolean —

whether the requested path matches the given route.

processTimers()

processTimers() 

Handles processing timers on this Atto Web Site. This method is called from the event loop in @see listen and checks to see if any callbacks associated with timers need to be called.

processRequestStreams()

processRequestStreams(resource  $server, array  $in_streams_with_data) 

Processes incoming streams with data. If the server has detected a new connection, then a stream is set-up. For other streams, request data is processed as it comes in. Once the request is complete, superglobals are set up and process() is used route the request which is output buffered. When this is complete, an output stream is instantiated to send this data asynchronously back to the browser.

Parameters

resource $server

socket server used to listen for incoming connections

array $in_streams_with_data

streams with request data to be processed.

processServerRequest()

processServerRequest(resource  $server) 

Used to process any timers for WebSite and used to check if the server has detected a new connection. In which case, a read stream is set-up.

Parameters

resource $server

socket server used to listen for incoming connections

initRequestStream()

initRequestStream(  $key) 

Gets info about an incoming request stream and uses this to set up an initial stream context. This context is used to populate the $_SERVER variable when the request is later processed.

Parameters

$key

processResponseStreams()

processResponseStreams(array  $out_streams_with_data) 

Used to send response data to out stream for which responses have not been written.

Parameters

array $out_streams_with_data

rout streams that are ready to send more response data

parseRequest()

parseRequest(integer  $key, string  $data) : boolean

Takes the string $data recently read from the request stream with id $key, tacks that on to the previous received data. If this completes an HTTP request then the request headers and request are parsed

Parameters

integer $key

id of request stream to process data for

string $data

from request stream

Returns

boolean —

whether the request is complete

setGlobals()

setGlobals(array  $context) 

Used to initialize the superglobals before process() is called when WebSite is run in CLI-mode. The values for the globals come from the request streams context which has request headers. If the request had CONTENT, for example, from posted form data, this is parsed and $_POST, and $_FILES superglobals set up.

Parameters

array $context

associative array of information parsed from a web request. The content portion of the request is not yet parsed but headers are, each with a prefix field HTTP_ followed by name of the header. For example the value of a header with name Cookie should be in $context['HTTP_COOKIE']. The Content-Type and Content-Length header do no get the prefix, so should be as $context['CONTENT_TYPE'] and $context['CONTENT_LENGTH']. The request method, querystring, also appear with the HTTP prefix. Finally, the content of the request should be in $context['CONTENT'].

defaultErrorHandler()

defaultErrorHandler(string  $route = "") 

Outputs HTTP error response message in the case that no specific error handler was set

Parameters

string $route

the route of the error. Internally, when an HTTP error occurs it is usually given a route of the form /response code. For example, /404 for a NOT FOUND error.

initializeBadRequestResponse()

initializeBadRequestResponse(integer  $key) 

Used to set up PHP superglobals, $_GET, $_POST, etc in the case that a 400 BAD REQUEST response occurs.

Parameters

integer $key

id of stream that bad request came from

cullDeadStreams()

cullDeadStreams() 

Used to close connections and remove from stream arrays streams that have not had traffic in the last CONNECTION_TIMEOUT seconds. The stream socket server is exempt from being culled, as are any streams whose ids are in $this->immortal_stream_keys.

shutdownHttpStream()

shutdownHttpStream(integer  $key) 

Closes stream with id $key and removes it from in_streams and outstreams arrays.

Parameters

integer $key

id of stream to delete

shutdownHttpWriteStream()

shutdownHttpWriteStream(integer  $key) 

Removes a stream from outstream arrays. Since an HTTP connection can handle several requests from a single client, this method does not close the connection. It might be run after a request response pair, while waiting for the next request.

Parameters

integer $key

id of stream to remove from outstream arrays.