CONNECTION
CONNECTION
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.
__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
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. |
__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.
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
|
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.
string | $route | request pattern to match |
\seekquarry\yioop\library\WebSite | $subsite | WebSite object to add sub routes from |
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.
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 |
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.
string | $method | the name of a web request method for example, "GET" |
string | $route | request pattern to match |
whether the $route was handled by any callback
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.
string | $header | HTTP header or message to send with HTTP response |
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.
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(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().
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(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
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 |
contents of the file given by $filename
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.
string | $filename | name of file to write to persistent storages |
string | $data | string of data to store in file |
number of bytes written
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
string | $filename | tmp_name in $_FILES of the uploaded file |
string | $destination | where on server the file should be moved to |
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
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. |
an id for the timer that can be used to turn it off (@see clearTimer())
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
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(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.
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. |
web page that WebSite would have reqsponded with if the request had been made as a usual web request.
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)
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 |
mime type or unknown if can't be determined
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
boolean | $include_headers | whether to include HTTP headers at beginning of reponse |
HTTP response to web client request
checkMatch(string $request_path, string $route) : boolean
Checks if a portion of a request uri path matches a Atto server route.
string | $request_path | part of a path portion of a request uri |
string | $route | a route that might be handled by Atto Server |
whether the requested path matches the given route.
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.
resource | $server | socket server used to listen for incoming connections |
array | $in_streams_with_data | streams with request data to be processed. |
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
integer | $key | id of request stream to process data for |
string | $data | from request stream |
whether the request is complete
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.
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(string $route = "")
Outputs HTTP error response message in the case that no specific error handler was set
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. |
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.
integer | $key | id of stream to remove from outstream arrays. |