Yioop_V9.5_Source_Code_Documentation

WebSite
in package

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.

Tags
author

Chris Pollett

Table of Contents

CONNECTION  = 0
CONTEXT  = 3
DATA  = 1
LEN_LONGEST_HTTP_METHOD  = 7
MODIFIED_TIME  = 2
REQUEST_HEAD  = 4
$base_path  : string
Used to determine portion of path to ignore when checking if a route matches against the current request.
$immortal_stream_keys  : array<string|int, mixed>
Keys of stream that won't disappear (for example the server socket)
$restart  : bool
Check if the current run of the website is after a restart
$stop  : bool
Used to signal stopping the website
$content_type  : bool
Whether the current response already has declared a Content-Type.
$current_session  : string
Cookie name value of the currently active request's session
$default_server_globals  : array<string|int, mixed>
Default values to write into $_SERVER before processing a connection request (in CLI mode)
$file_cache  : array<string|int, mixed>
Used to cache in RAM files which have been read or written by the fileGetContents or filePutContents
$header_data  : string
Holds the header portion so far of the HTTP response
$http_methods  : array<string|int, mixed>
List of HTTP methods for which routes have been declared
$in_streams  : array<string|int, mixed>
Array of all connection streams for which we are receiving data from client together with associated stream info
$is_cli  : bool
Whether this object is being run from the command line with a listen() call or if it is being run under a web server and so only used for routing
$is_secure  : bool
Whether https is being used
$middle_wares  : array<string|int, mixed>
Middle ware callbacks to run when processing a request
$out_streams  : array<string|int, mixed>
Array of all connection streams for which we are writing data to a client together with associated stream info
$request_script  : array<string|int, mixed>
Filename of currently requested script
$routes  : array<string|int, mixed>
Associative array http_method => array of how to handle paths for that method
$session_configs  : array<string|int, mixed>
Default values used to set up session variables
$session_queue  : array<string|int, mixed>
Keeps an ordering of currently actively sessions so if run out of memory know who to evict
$sessions  : array<string|int, mixed>
Used to store session data in ram for all currently active sessions
$timer_alarms  : SplMinHeap
Priority queue of which timers are about to go off
$timers  : array<string|int, mixed>
Timer function callbacks that have been declared
__call()  : mixed
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.
__construct()  : mixed
Sets the base path used for determining request routes. Sets precision for timed events and sets up timer heap and other field variables
addRoute()  : mixed
Generic function for associating a function $callback to be called when a web request using $method method and with a uri matching $route occurs.
clearFileCache()  : mixed
Deletes the files stored in the RAM FileCache
clearTimer()  : mixed
Deletes a timer for the list of active timers. (@see setTimer)
fileGetContents()  : string
Reads in the file $filename and returns its contents as a string.
filePutContents()  : int
Writes $data to the persistent file with name $filename. Saves a copy in the RAM cache if there is a copy already there.
getSessions()  : mixed
Used to export info (but not change) about running sessions
header()  : mixed
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.
isCli()  : bool
Returns whether this class is being used from the command-line or in a web server/cgi setting
listen()  : mixed
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.
middleware()  : mixed
Adds a middle ware callback that should be called before any processing on the request is done.
mimeType()  : string
Returns the mime type of the provided file name if it can be determined.
moveUploadedFile()  : mixed
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
process()  : mixed
Cause all the current HTTP request to be processed according to the middleware callbacks and routes currently set on this WebSite object.
processInternalRequest()  : 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.
sessionStart()  : mixed
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().
setCookie()  : mixed
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();
setTimer()  : int
Sets up a repeating or one-time timer that calls $callback every or after $time seconds
subsite()  : mixed
Used to add all the routes and callbacks of a WebSite object to the current WebSite object under paths matching $route.
trigger()  : bool
Calls any callbacks associated with a given $method and $route provided that recursion in method route call is not detected.
checkMatch()  : bool
Checks if a portion of a request uri path matches a Atto server route.
cullDeadStreams()  : mixed
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.
defaultErrorHandler()  : mixed
Outputs HTTP error response message in the case that no specific error handler was set
getResponseData()  : 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
initializeBadRequestResponse()  : mixed
Used to set up PHP superglobals, $_GET, $_POST, etc in the case that a 400 BAD REQUEST response occurs.
initRequestStream()  : mixed
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.
parseRequest()  : bool
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
processRequestStreams()  : mixed
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.
processResponseStreams()  : mixed
Used to send response data to out stream for which responses have not been written.
processServerRequest()  : mixed
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.
processTimers()  : mixed
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.
setGlobals()  : mixed
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.
shutdownHttpStream()  : mixed
Closes stream with id $key and removes it from in_streams and outstreams arrays.
shutdownHttpWriteStream()  : mixed
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.

Constants

CONNECTION

public mixed CONNECTION = 0

LEN_LONGEST_HTTP_METHOD

public mixed LEN_LONGEST_HTTP_METHOD = 7

MODIFIED_TIME

public mixed MODIFIED_TIME = 2

REQUEST_HEAD

public mixed REQUEST_HEAD = 4

Properties

$base_path

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

public string $base_path

$immortal_stream_keys

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

public array<string|int, mixed> $immortal_stream_keys = []

$restart

Check if the current run of the website is after a restart

public bool $restart

$stop

Used to signal stopping the website

public bool $stop

$content_type

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

protected bool $content_type

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

$current_session

Cookie name value of the currently active request's session

protected string $current_session = ""

$default_server_globals

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

protected array<string|int, mixed> $default_server_globals

$file_cache

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

protected array<string|int, mixed> $file_cache = ['MARKED' => [], 'UNMARKED' => [], 'PATH' => []]

$header_data

Holds the header portion so far of the HTTP response

protected string $header_data

$http_methods

List of HTTP methods for which routes have been declared

protected array<string|int, mixed> $http_methods

$in_streams

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

protected array<string|int, mixed> $in_streams = []

$is_cli

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

protected bool $is_cli

$is_secure

Whether https is being used

protected bool $is_secure = false

$middle_wares

Middle ware callbacks to run when processing a request

protected array<string|int, mixed> $middle_wares = []

$out_streams

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

protected array<string|int, mixed> $out_streams = []

$request_script

Filename of currently requested script

protected array<string|int, mixed> $request_script

$routes

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

protected array<string|int, mixed> $routes = ["CONNECT" => [], "DELETE" => [], "ERROR" => [], "GET" => [], "HEAD" => [], "OPTIONS" => [], "POST" => [], "PUT" => [], "TRACE" => []]

$session_configs

Default values used to set up session variables

protected array<string|int, mixed> $session_configs = ['cookie_lifetime' => '0', 'cookie_path' => '/', 'cookie_domain' => '', 'cookie_secure' => '', 'cookie_httponly' => '', 'name' => 'PHPSESSID', 'save_path' => '']

$session_queue

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

protected array<string|int, mixed> $session_queue = []

$sessions

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

protected array<string|int, mixed> $sessions = []

$timer_alarms

Priority queue of which timers are about to go off

protected SplMinHeap $timer_alarms

$timers

Timer function callbacks that have been declared

protected array<string|int, mixed> $timers = []

Methods

__call()

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.

public __call(string $method, array<string|int, mixed> $route_callback) : mixed
Parameters
$method : string

HTTP command to add $route_callack for in routing table

$route_callback : array<string|int, mixed>

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
Return values
mixed

__construct()

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

public __construct([string $base_path = "" ]) : mixed
Parameters
$base_path : string = ""

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.

Return values
mixed

addRoute()

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

public addRoute(string $method, string $route, callable $callback) : mixed
Parameters
$method : string

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

$route : string

request pattern to match

$callback : callable

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

Return values
mixed

clearFileCache()

Deletes the files stored in the RAM FileCache

public clearFileCache() : mixed
Return values
mixed

clearTimer()

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

public clearTimer(int $timer_id) : mixed
Parameters
$timer_id : int

the id of the timer to remove

Return values
mixed

fileGetContents()

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

public fileGetContents(string $filename[, bool $force_read = false ]) : 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
$filename : string

name of file to get contents of

$force_read : bool = false

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

Return values
string

contents of the file given by $filename

filePutContents()

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

public filePutContents(string $filename, string $data) : int
Parameters
$filename : string

name of file to write to persistent storages

$data : string

string of data to store in file

Return values
int

number of bytes written

getSessions()

Used to export info (but not change) about running sessions

public getSessions() : mixed
Return values
mixed

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.

public header(string $header) : mixed
Parameters
$header : string

HTTP header or message to send with HTTP response

Return values
mixed

isCli()

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

public isCli() : bool
Return values
bool

whether the class is being run from the command line

listen()

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.

public listen(int $address[, mixed $config_array_or_ini_filename = false ]) : mixed

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

Parameters
$address : int

address and port to listen for web requests on

$config_array_or_ini_filename : mixed = false

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.)

Return values
mixed

middleware()

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

public middleware(callable $callback) : mixed
Parameters
$callback : callable

function to be called before processing of request

Return values
mixed

mimeType()

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

public static mimeType(string $file_name[, bool $use_extension = false ]) : string

(This function is from the seekquarry/yioop project)

Parameters
$file_name : string

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

$use_extension : bool = false

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

Return values
string

mime type or unknown if can't be determined

moveUploadedFile()

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

public moveUploadedFile(string $filename, string $destination) : mixed
Parameters
$filename : string

tmp_name in $_FILES of the uploaded file

$destination : string

where on server the file should be moved to

Return values
mixed

process()

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

public process() : mixed
Return values
mixed

processInternalRequest()

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.

public processInternalRequest(string $url[, bool $include_headers = false ][, array<string|int, mixed> $post_data = null ]) : string

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
$url : string

local page url requested

$include_headers : bool = false

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

$post_data : array<string|int, mixed> = null

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

Return values
string

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

sessionStart()

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().

public sessionStart([array<string|int, mixed> $options = [] ]) : mixed
Parameters
$options : array<string|int, mixed> = []

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'

Return values
mixed

setCookie()

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();

public setCookie(string $name[, string $value = "" ], int $expire[, string $path = "" ][, string $domain = "" ][, string $secure = false ][, bool $httponly = false ]) : mixed

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

Parameters
$name : string

name of cookie

$value : string = ""

value associated with cookie

$expire : int

Unix timestamp for when the cookie expires

$path : string = ""

request path associated with the cookie

$domain : string = ""

request domain associated with the cookie

$secure : string = false

whether the cookie should only be sent if HTTPS in use

$httponly : bool = false

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

Return values
mixed

setTimer()

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

public setTimer(float $time, callable $callback[, bool $repeating = true ]) : int
Parameters
$time : float

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

$callback : callable

a function to be called after now + $time

$repeating : bool = true

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

Return values
int

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

subsite()

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

public subsite(string $route, WebSite $subsite) : mixed
Parameters
$route : string

request pattern to match

$subsite : WebSite

WebSite object to add sub routes from

Return values
mixed

trigger()

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

public trigger(string $method, string $route) : bool
Parameters
$method : string

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

$route : string

request pattern to match

Return values
bool

whether the $route was handled by any callback

checkMatch()

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

protected checkMatch(string $request_path, string $route) : bool
Parameters
$request_path : string

part of a path portion of a request uri

$route : string

a route that might be handled by Atto Server

Return values
bool

whether the requested path matches the given route.

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.

protected cullDeadStreams() : mixed
Return values
mixed

defaultErrorHandler()

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

protected defaultErrorHandler([string $route = "" ]) : mixed
Parameters
$route : string = ""

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.

Return values
mixed

getResponseData()

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

protected getResponseData([bool $include_headers = true ]) : string
Parameters
$include_headers : bool = true

whether to include HTTP headers at beginning of response

Return values
string

HTTP response to web client request

initializeBadRequestResponse()

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

protected initializeBadRequestResponse(int $key) : mixed
Parameters
$key : int

id of stream that bad request came from

Return values
mixed

initRequestStream()

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.

protected initRequestStream(mixed $key) : mixed
Parameters
$key : mixed
Return values
mixed

parseRequest()

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

protected parseRequest(int $key, string $data) : bool
Parameters
$key : int

id of request stream to process data for

$data : string

from request stream

Return values
bool

whether the request is complete

processRequestStreams()

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.

protected processRequestStreams(resource $server, array<string|int, mixed> $in_streams_with_data) : mixed
Parameters
$server : resource

socket server used to listen for incoming connections

$in_streams_with_data : array<string|int, mixed>

streams with request data to be processed.

Return values
mixed

processResponseStreams()

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

protected processResponseStreams(array<string|int, mixed> $out_streams_with_data) : mixed
Parameters
$out_streams_with_data : array<string|int, mixed>

rout streams that are ready to send more response data

Return values
mixed

processServerRequest()

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.

protected processServerRequest(resource $server) : mixed
Parameters
$server : resource

socket server used to listen for incoming connections

Return values
mixed

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.

protected processTimers() : mixed
Return values
mixed

setGlobals()

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.

protected setGlobals(array<string|int, mixed> $context) : mixed
Parameters
$context : array<string|int, mixed>

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, query_string, also appear with the HTTP_ prefix. Finally, the content of the request should be in $context['CONTENT'].

Return values
mixed

shutdownHttpStream()

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

protected shutdownHttpStream(int $key) : mixed
Parameters
$key : int

id of stream to delete

Return values
mixed

shutdownHttpWriteStream()

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.

protected shutdownHttpWriteStream(int $key) : mixed
Parameters
$key : int

id of stream to remove from outstream arrays.

Return values
mixed

        

Search results