A small and simple web framework built using PHP. Handles routing and different request methods.
This projects was made so that I would have a way of creating simple REST APIs on my server, since most of the existing PHP projects were either way more complex than I liked or required Composer or some other installation requirement. Size was another concern, I didn't want to have to deal with the following things for every small REST API on my server:
a bunch of small files littering my server,large packages,a bunch of package dependencies to keep track of.
While this is intended to be a small framework with close to native performance, I will still consider feature requests, but keep in-mind that I might reject your request if it doesn't align with the ethos of this project.
- Route-based middlewares? (unsure about this one since it would add quite a bit of complexity and can still be handled using a global middleware)
- Add more comments
- Add more tests
- Add example projects
- Further expand documentation?
- Installation
- Error codes
- Constructor options
- Request data
- Route loading
- Routing
- Global middleware
- Redirection
- HTTP host and URI utilities
- Sending responses
- Moving uploaded files
- HTML rendering
- View rendering
- Authentication
- Custom 404 response
- Custom error handler
- Custom headers
- Helmet
- CORS
Go download version 0.4.0 (latest release).
The
mainbranch can also be downloaded, but may include code that hasn't been properly tested yet or changes that break old code. I really recommend sticking to releases rather than using themainbranch.
Add WebFramework.php to your project and require it in index.php. To allow for routing a .htaccess file is used for Apache and nginx.conf for Nginx (or sites-available/DOMAIN).
This framework requires PHP 8.0+ to work, this is due to the usage of the
objecttype hint and the use ofstr_starts_withandstr_ends_with.
/index.php
<?php
require_once("./classes/WebFramework.php");
$webFramework = new WebFramework(); // default with auto loading from "routes" folder
// ... optional manual loading of additional routes ...
$webFramework->start(); // runs last (after all routes have been loaded)
?>Option 1: .htaccess when running framework at domain root [https://example.com/]
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [QSA,L]
# if forcing of https is wanted (excluding localhost)
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} !^(localhost|127\.0\.0\.1)(:[0-9]+)?$
RewriteRule ^.*$ https://%{HTTP_HOST}%{REQUEST_URI} [R,L]Option 2: .htaccess when running framework inside a folder [https://example.com/my_api/]
RewriteEngine On
RewriteBase /my_api/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [QSA,L]
# if forcing of https is wanted (excluding localhost)
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} !^(localhost|127\.0\.0\.1)(:[0-9]+)?$
RewriteRule ^.*$ https://%{HTTP_HOST}%{REQUEST_URI} [R,L]Option 3: nginx.conf when running framework at domain root [https://example.com/]
Since forcing SSL can be handled independently of this addition it won't be included in this example.
server {
# ... other config items ...
rewrite ^/(.*)$ /index.php last;
}Option 4: nginx.conf when running framework inside a folder [https://example.com/my_api/]
Since forcing SSL can be handled independently of this addition it won't be included in this example.
server {
# ... other config items ...
rewrite ^/my_api/(.*)$ /my_api/index.php last;
}You can easily customize the default error handler that is provided. This error handler will deal with fatal errors and exceptions.
- E10000: Uncaught exception caused by loaded routes or other custom code.
- E10001: Error sent using
trigger_error(handled byset_error_handler). - E10002: Fatal error caught by the shutdown function (e.g.
E_ERROR,E_PARSE,E_CORE_ERROR,E_COMPILE_ERROR). - E11000: Error sent from
_load_routes, caused by givenroutes_foldernot being a folder or not being readable. - E11111: Default fallback error code used by
_send_errorwhen no specific code is provided. - E20000: Error sent from
send_jsonorsend_json_body, caused by failed JSON encode. - E20001: Error sent from
send, caused by an invalid HTTP status code (code must be: 100-599). - E20002: Error sent from
send_json_body, caused by an invalidstatusin$databody (must be a number: 100-599). - E50000: Error sent from
render_view, caused by missing or unreadable file at the given$view_str.
Note:
send_file()andmove_uploaded_file()do not use the_send_errorscheme above. Instead they throw nativeExceptions with their own smaller error codes (see the respective "Exceptions" sections below). It is recommended to wrap calls to these two methods in atry/catchblock.
Default values:
array(
"routes_folder" => "routes",
"views_folder" => "views",
"handle_php_errors" => true,
"use_json_error_handler" => false,
"debug_mode" => false,
"include_status_code_in_sent_json" => true,
"use_error_log_in_error_handler" => true,
"always_use_helmet" => true
);Example:
$webFramework = new WebFramework(array(
"debug_mode" => true,
"include_status_code_in_sent_json" => false
));Will change the folder used for auto-loading routes.
Will change the folder that render_view() uses to find view files.
Wether WebFrameworkPHP should handle PHP exceptions and errors (a default error handler function is also provided), if disabled then the default PHP error handling is used. This must be turned on if you want to use set_custom_error_handler().
Wether the default error handler function provided by WebFrameworkPHP should output the error as JSON.
Example:
{
"status": 500,
"error": "...",
"error_code": 10000
}Wether the default error handler function provided by WebFrameworkPHP should provide detailed errors. This can make debugging much easier, but can also include details that you don't want users to see, as such this should not be turned on in a production deployment.
Can also be activated using $webFramework->debug_mode = true; (must be run before start()).
This option can also be used inside routes to provide more information while running in debug mode.
Wether send_json and send_json_body should include "status": 200 in the response body. This toggles it globally, it can always be toggled on a per call basis by passing appropriate option to send_json or send_json_body.
Wether the default error handler function provided by WebFrameworkPHP should also use error_log to log more detailed errors. This can be useful if you don't want to turn on debug mode, but still want to see the more detailed errors.
Error is sent to PHP's system logger, using the Operating System's system logging mechanism or a file, depending on what the error_log configuration directive is set to. An option to change this might be added in the future.
Wether helmet should be called before every response. If this is not disabled then using helmet manually will do nothing. If disabled helmet can still be used globally or on a per route basis by manually calling the method.
request->uriwill always exclude the current directory, if you are running the framework from the domain root then this will not affect you. However if you are running from inside a folder, the URI will never include the folder, e.g./my_api/hellobecomes/hello.
Structure of request data:
$this->request = (object) array(
"method" => $_SERVER["REQUEST_METHOD"], // HTTP method of the request
"content_type" => $_SERVER["CONTENT_TYPE"], // Content-Type of the request
"uri" => "...", // the current URI
"credentials" => array(...), // the parsed basic authentication credentials of the request (only gets parsed if the parse_auth() method is called before start()) [will be null if not found]
"token" => "...", // the parsed bearer token of the request (only gets parsed if the parse_auth() method is called before start()) [will be null if not found]
"query" => array(...), // parsed URI queries (?hello=world&abc=123)
"params" => array(...), // parsed URI params (/:hello/:abc)
"body" => array(...), // parsed post data (form-data, x-www-form-urlencoded, raw[application/json]) (will not be parsed if HTTP method is "GET")
"files" => array(...), // parsed files data (will not be parsed if HTTP method is "GET")
);Example:
curl -X POST 'https://example.com/api/note/12345678/?type=sticky'\
-H 'Authorization: Bearer my_secret_token'\
-H "Content-type: application/json"\
-d '{ "title": "My sticky note", "contents": "Remember Sunday" }'$this->post("/note/:id", function() {
$this->request->token; // "my_secret_token" (can be null, either if Bearer token parsing wasn't enabled using parse_auth() or if a valid HTTP header couldn't be found in the request)
$this->request->params["id"]; // "12345678" (required)
$this->request->query["type"]; // "sticky" (can be missing, using isset() before accessing is recommended)
$this->request->body["title"]; // "My sticky note" (can be missing, using isset() before accessing is recommended)
$this->request->body["contents"]; // "Remember Sunday" (can be missing, using isset() before accessing is recommended)
return $this->send("Note added");
}All routing is done by placing PHP files inside either the default
routesfolder, or by choosing your own folder in the constructor options. Auto loading of routes can be disabled by passing an empty string to the constructor optionroutes_folder(e.g."routes_folder" => ""). Auto loading can used together with manual loading of additional routes.
Files starting with
.or_will be ignored.
/index.php
<?php
require_once("./classes/WebFramework.php");
$webFramework = new WebFramework();
$webFramework->start();
?>/routes/demo.php
<?php
$this->get("/demo", function() {
return $this->send_json(array(
"message" => "Hello world!",
), 200);
});
// ... additional paths ...
?>/index.php
<?php
require_once("./classes/WebFramework.php");
$webFramework = new WebFramework(array(
"routes_folder" => "" // disables auto loading
));
require_once("./manual_route.php");
$webFramework->start();
?>/manual_route.php
<?php
$webFramework->get("/manual", function() use($webFramework) {
return $webFramework->send_json_body(array(
"status" => 200,
"message" => "Hello world!",
));
});
// ... additional paths ...
?>The following HTTP methods are available:
ALL(special),GET,POST,PUT,PATCH,DELETE. URI queries in the route URI will be ignored, e.g."/document?hello=world"will resolve to/document, as such URI queries should not be used in the route URI. Theall()method can be used to load a route for all HTTP methods.
<?php
// example #1: special "ALL" request handling (will handle GET, POST, PUT, etc.)
$this->all("/info", function() {
return $this->send_json_body(array(
"status" => 200,
"message" => "...",
));
});
// example #2: GET request handling
$this->get("/document", function() {
// ... documents ...
return $this->send_json_body(array(
"status" => 200,
"message" => "Fetched all documents!",
"documents" => array [...],
));
});
// example #3: GET request handling, with URI param
$this->get("/document/:id", function() {
$document_id = $this->request->params["id"];
// ... fetch document ...
return $this->send_json_body(array(
"status" => 200,
"message" => "Fetched single document!",
"document" => object {...},
));
});
// example #4: POST request handling
$this->post("/document", function() {
$document_title = $this->request->body["title"];
$document_contents = $this->request->body["contents"];
// ... create document ...
return $this->send_json_body(array(
"status" => 200,
"message" => "New document added!",
"id" => $document_id
));
});
?>Route arguments can be added to easily pass data that needs to be used by a middleware or code running inside a rendered view.
One example use case for this is passing
"auth" => trueas an argument, then check in a middleware if the defined route requires authentication and only check for an auth token if that is provided. This solves the issue of having to check for authentication on every route or having to check the URI to know if it should have authentication or not.
<?php
// example #1: special "ALL" request handling (will handle GET, POST, PUT, etc.)
$this->all("/info", function() {
return $this->send_json_body(array(
"status" => 200,
"message" => "...",
"route_arg" => (isset($this->route->args["my_arg"]) ? $this->route->args["my_arg"] : "")
));
}, array("my_arg" => "my_important_value"));
// example #2: GET request handling
$this->get("/document", function() {
// ... documents ...
return $this->send_json_body(array(
"status" => 200,
"message" => "Fetched all documents!",
"documents" => array [...],
"route_arg" => (isset($this->route->args["my_arg"]) ? $this->route->args["my_arg"] : "")
));
}, array("my_arg" => "my_important_value"));
// example #3: render view handling (see below example of document view, labeled `/views/document.php`)
$this->render_view("/document/:id", "document", array("my_arg" => "my_important_value"));
?>/views/document.php
<?php
// ... logic to fetch document ...
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document viewer</title>
</head>
<body>
<h1><?php echo $document->title; ?></h1>
<main>
<p><?php echo (isset($this->route->args["my_arg"]) ? $this->route->args["my_arg"] : ""); ?></p>
<p><?php echo $document->contents; ?></p>
</main>
</body>
</html>Allows to run code before any route runs, this can be useful for authentication checks, using any of the
sendmethods will stop execution of any routes. Route specific middleware might be supported in the future, but a similar function can already be accomplished by checking the value of$webFramework->route->uri.
A global middleware is added by calling the
add_middleware()method. Multiple middleware can be added, but they must all be added before the call tostart().
Example:
<?php
require_once("./classes/WebFramework.php");
require_once("./classes/Auth.php");
$webFramework = new WebFramework();
$webFramework->parse_auth(); // this can either be placed here or inside the middleware (just make sure do not add it in two places) [recommended]
$webFramework->add_middleware(function() use($webFramework) {
$route_args = $webFramework->route->args;
$is_auth_required = (isset($route_args["auth"]) ? $route_args["auth"] : false);
if($is_auth_required === true) {
$webFramework->parse_auth(); // this can either be placed here or anytime before the adding of this middleware (just make sure do not add it in two places)
if($webFramework->request->token === null) {
return $webFramework->send("Missing valid auth token!", 403); // stops any route from being run
}
if(Auth::is_valid_token($webFramework->request->token) === false) {
return $webFramework->send("Invalid auth token!", 403); // stops any route from being run
}
}
});
$webFramework->start();
?>Redirection function, allows you to redirect the user to a different URL. The status code is set to
301for permanent redirects and302for temporary redirects.
function redirect(string $redirect_uri, bool $permanent = false)Examples:
$this->redirect("https://example.com");
$this->redirect("https://example.com", true);Redirection function, allows you to redirect the user to a local route. The status code is set to
301for permanent redirects and302for temporary redirects. Local redirection cannot escape from the root URI. As such if the framework isn't running from the root of the domain then the redirection will always be prefixed with the folder it's running inside.
function local_redirect(string $route_str, bool $permanent = false)Examples:
$this->local_redirect("/my/local/route"); // "https://example.com/my/local/route"
// If the framework isn't running from the root of the domain then the folder will be included in the end result
$this->local_redirect("/my/local/route"); // "https://example.com/my_api/my/local/route"Path conversion function, returns a path prefixed with the root URI.
function to_local_uri(string $path)Examples:
$this->to_local_uri("/my/local/route"); // "/my/local/route"
$this->to_local_uri("my/local/route"); // "/my/local/route"
// If the framework isn't running from the root of the domain then the folder will be included in the end result
$this->to_local_uri("/my/local/route"); // "/my_api/my/local/route"
$this->to_local_uri("my/local/route"); // "/my_api/my/local/route"Path conversion function, returns a path prefixed with the HTTP host and root URI.
function to_public_uri(string $path, bool $always_https = false)Examples:
$this->to_public_uri("/my/local/route"); // "https://example.com/my/local/route"
$this->to_public_uri("my/local/route"); // "https://example.com/my/local/route"
// If the framework isn't running from the root of the domain then the folder will be included in the end result
$this->to_public_uri("/my/local/route"); // "https://example.com/my_api/my/local/route"
$this->to_public_uri("my/local/route"); // "https://example.com/my_api/my/local/route"HTTP host function, returns the server's HTTP host with port number appended (if the port is not 80 or 443) and prefixes http or https.
function get_http_host(bool $always_https = false)Examples:
$this->get_http_host(); // "http://example.com" or "https://example.com" depending on the current request scheme
$this->get_http_host(true); // always "https://example.com"Request URI function, returns the current request URI prefixed with the HTTP host and root URI
function get_public_request_uri(bool $always_https = false)Examples:
$this->get_public_request_uri(); // "http://example.com/my/request/uri" or "https://example.com/my/request/uri" depending on the current request scheme
$this->get_public_request_uri(true); // always "https://example.com/my/request/uri"Responses can either be sent using
send(...),send_json(...),send_json_body(...)orsend_file(...). Responses exit PHP, so after they are sent no other code will be run.
Base response function, allows you to send any data you want with any Content-Type and status code. HTTP status code must be a number (100-599).
function send(string $data, int $status_code = 200, string $content_type = "text/plain")Examples:
$this->send("Hello world!"); // 200 OK
$this->send("Hello world!", 400); // 400 Bad Request
$this->send("Hello world!", 500); // 500 Internal Error
$this->send(json_encode(array(...)), 200, "application/json"); // 200 OKJSON response function, allows you to send data as JSON. Response will always have the Content-Type of
application/json. Status code is chosen by setting$status_code.$datacan either be an associative array or an object. HTTP status code must be a number (100-599).
$include_status_codecontrols whether"status": <code>is included in the response body. When left asnull(the default), the value of theinclude_status_code_in_sent_jsonconstructor option is used. Passtrueorfalseto override it for this call only.
function send_json(object|array $data, int $status_code = 200, bool|null $include_status_code = null)Examples:
$this->send_json(array(
"hello" => "world!",
)); // 200 OK
$this->send_json(array(
"hello" => "world!",
), 200); // 200 OK
$this->send_json(array(
"hello" => "world!",
), 400); // 400 Bad Request
$this->send_json(array(
"hello" => "world!",
), 500); // 500 Internal ErrorJSON response function, allows you to send data as JSON. Response will always have the Content-Type of
application/json. Status code is chosen by passingstatusin the$dataobject/array.$datacan either be an associative array or an object. Ifstatusis omitted from$datathen it will default to200. HTTP status code must be a number (100-599).
$include_status_codecontrols whether"status": <code>is included in the response body. When left asnull(the default), the value of theinclude_status_code_in_sent_jsonconstructor option is used. Passtrueorfalseto override it for this call only.
function send_json_body(object|array $data, bool|null $include_status_code = null)Examples:
$this->send_json_body(array(
"hello" => "world!",
)); // 200 OK
$this->send_json_body(array(
"status" => 200,
"hello" => "world!",
)); // 200 OK
$this->send_json_body(array(
"status" => 400,
"hello" => "world!",
)); // 400 Bad Request
$this->send_json_body(array(
"status" => 500,
"hello" => "world!",
)); // 500 Internal ErrorFile response function, allows you to send files. Response will automatically choose the Content-Type if
finfois supported (will throw an exception if it's not supported and a Content-Type isn't provided using$content_type).$download_file_namewill change the file name displayed to the user.$streamenables chunked output and HTTP range requests (useful for large files or in-browser media playback).$dispositioncontrols how the browser handles the file.
Status codes: When not streaming, the status is
200 OK. When$streamis enabled and the client sends a validRangeheader, the response will be206 Partial Content; invalid/unsatisfiable ranges result in416 Range Not Satisfiable.
$dispositionaccepts"attachment"(force a download, default) or"inline"(display/play the file in the browser). Any unexpected value falls back to"attachment".
function send_file(
string $file_path,
string|null $download_file_name = null,
string|null $content_type = null,
bool $stream = false,
string $disposition = "attachment"
)- If no file is found at the provided
$file_path, an exception with error code1000is thrown. - If the file provided by
$file_pathis not readable, an exception with error code1001is thrown. - If no
$content_typeis provided and thefileinfo(finfo) extension isn't loaded, an exception with error code2000is thrown. - If the file provided by
$file_pathfailed to open for reading, an exception with error code3000is thrown. - If seeking within the file fails (during a range request), an exception with error code
3001is thrown. - If reading the file fails during output, an exception with error code
3002is thrown.
Examples:
// wrapping send_file() in a try block is recommended, since it throws exceptions when errors are encountered
try {
return $this->send_file("hello_world.txt");
} catch(Exception $err) {
return $this->send_json_body(array(
"status" => 500,
"error" => $err->getMessage(),
"error_code" => $err->getCode()
));
}
// Custom download name shown to the user
try {
return $this->send_file("hello_world.txt", "i_show_up_differently_to_the_user.txt");
} catch(Exception $err) {
return $this->send_json_body(array(
"status" => 500,
"error" => $err->getMessage(),
"error_code" => $err->getCode()
));
}
// Stream a video for in-browser playback (supports seeking via range requests)
try {
return $this->send_file("clip.mp4", null, null, true, "inline");
} catch(Exception $err) {
return $this->send_json_body(array(
"status" => 500,
"error" => $err->getMessage(),
"error_code" => $err->getCode()
));
}This function moves an uploaded file to a specified location. Returns the uploaded file's path on success.
function move_uploaded_file(string $file, string $dest_folder = ".", array $options = array()): string- If no files are found in the request, an exception with error code
1000is thrown. - If the uploaded file is not found under the property name provided by
$file, an exception with error code1001is thrown. - If an error occurs with the upload, an exception with error code
1002is thrown. - If the uploaded file does not have a valid extension as specified with the
allowed_extsoption, an exception with error code2000is thrown. - If the uploaded file is smaller than specified with the
min_sizeoption, an exception with error code2001is thrown. - If the uploaded file is larger than specified with the
max_sizeoption, an exception with error code2002is thrown. - If the uploaded file has a potentially executable/dangerous extension that is not explicitly allowed via
allowed_exts, an exception with error code2003is thrown. This check also applies to any extension set via thenew_file_extoption. - If the specified
$dest_folderis not a folder or does not exist, an exception with error code3000is thrown. - If the specified folder path by
$dest_folderis not writeable, an exception with error code3001is thrown. - If the file cannot be moved, an exception with error code
4000is thrown.
Security note: Regardless of the
allowed_extsoption, the following extensions are always blocked unless you explicitly include them inallowed_exts: anyphp/phpNvariant,pht,phtm,phtml,phps,phar,pcgi,inc,htaccess,shtml,cgi,pl. For production use, it is strongly recommended to always set an explicitallowed_extswhitelist.
all of these options are optional.
array(
"new_file_name" => "...", // what you want the file to be named on the server (should not include extension)
"new_file_ext" => "...", // what extension you want the file to have on the server
"allowed_exts" => array(...), // an array of strings of which extensions are allowed (should not include dot)
"min_size" => 0, // an integer of how small the file can be (in bytes, e.g. `1000` bytes, then no files under 1 kilobytes will be allowed)
"max_size" => 0, // an integer of how large the file can be (in bytes, e.g. `5 * pow(10, 6)` bytes, then no files over 5 megabytes will be allowed)
"remove_invalid_files" => true, // wether the file should be removed from the server if it's deemed invalid by ext or size (true by default)
)Examples:
// Example 1: move the file uploaded with data field "cv", keeping the original file name.
// wrapping move_uploaded_file() in a try block is recommended, since it throws exceptions when errors are encountered
try {
// moves the file uploaded under the name "cv" to the "uploaded_files" folder
$uploaded_file = $this->move_uploaded_file("cv", "uploaded_files"); // returns the uploaded file's path (e.g. "uploaded_files/John Doe - CV.pdf")
return $this->send_json_body(array(
"status" => 200,
"message" => "Thank you for uploading your CV.",
"uploaded_path" => $uploaded_file
));
} catch(Exception $err) {
return $this->send_json_body(array(
"status" => 400,
"error" => $err->getMessage(),
"error_code" => $err->getCode()
));
}
// Example 2: move the file uploaded with data field "cv", setting the file name to the current Unix Epoch.
// wrapping move_uploaded_file() in a try block is recommended, since it throws exceptions when errors are encountered
try {
// moves the file uploaded under the name "cv" to the "uploaded_files" folder
$uploaded_file = $this->move_uploaded_file("cv", "uploaded_files", array(
"new_file_name" => "cv-" . time(),
"allowed_exts" => array("pdf") // only allow PDFs
)); // returns the uploaded file's path (e.g. "uploaded_files/cv-1660338149.pdf")
return $this->send_json_body(array(
"status" => 200,
"message" => "Thank you for uploading your CV.",
"uploaded_path" => $uploaded_file
));
} catch(Exception $err) {
return $this->send_json_body(array(
"status" => 400,
"error" => $err->getMessage(),
"error_code" => $err->getCode()
));
}A HTTP method can be specified, the allowed values are:
ALL,GET,POST,PUT,PATCH,DELETE. The provided method does not have to be all uppercase. Route arguments can be passed via$route_args(see Route arguments).
function render_html(
string $route_str,
callable $route_callback,
array $route_args = array(),
int $status_code = 200,
string $method = "GET"
)Examples:
/routes/root.php
<?php $this->render_html("/", function() { ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hello world!</title>
</head>
<body>
<p>Hello world! <?php echo $this->request->uri; ?></p>
</body>
</html>
<?php }); ?>/routes/document.php
<?php
$this->render_html("/document/:id", function() {
// ... logic to fetch document ...
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document viewer</title>
</head>
<body>
<h1><?php echo $document->title; ?></h1>
<main><?php echo $document->contents; ?></main>
</body>
</html>
<?php }, 200); ?>A HTTP method can be specified, the allowed values are:
ALL,GET,POST,PUT,PATCH,DELETE. The provided method does not have to be all uppercase. Route arguments can be passed via$route_args(see Route arguments).
function render_view(
string $route_str,
string $view_str,
array $route_args = array(),
int $status_code = 200,
string $method = "GET"
)
$view_strshould be the name of the file inside theviewsfolder. Sodocumentwould turn intoviews/document.php,hello/worldwould turn intoviews/hello/world.php.
Examples:
/routes/main.php
<?php
$this->render_view("/", "main");
$this->render_view("/document/:id", "document");
?>/views/main.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hello world!</title>
</head>
<body>
<p>Hello world! <?php echo $this->request->uri; ?></p>
</body>
</html>/views/document.php
<?php
// ... logic to fetch document ...
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document viewer</title>
</head>
<body>
<h1><?php echo $document->title; ?></h1>
<main><?php echo $document->contents; ?></main>
</body>
</html>You can use the provided parse_auth() method to parse for a Bearer token. If a valid Authorization HTTP header is found and the parsing is successful then the token will be added to request->token. If no valid token can be found then request->token will be null.
Example:
<?php
require_once("./classes/WebFramework.php");
$webFramework = new WebFramework();
$webFramework->parse_auth(); // activate parsing of Basic Authentication & Bearer tokens
$webFramework->get("/protected", function() use($webFramework) {
$token = $webFramework->request->token;
if($token === null) {
return $webFramework->send_json_body(array(
"status" => 403,
"message" => 'Missing or invalid Authorization header provided (use: "Authorization: Bearer ...")!',
));
}
if($token !== "secret_token") {
return $webFramework->send_json_body(array(
"status" => 403,
"message" => 'Provided token is invalid!',
));
}
return $webFramework->send_json_body(array(
"status" => 200,
"message" => "Hello protected world!",
));
});
$webFramework->start();
?>You can use the provided parse_auth() method to parse for Basic Authentication requests. If a valid Authorization HTTP header is found and the parsing is successful then the provided username and password will be added to request->credentials. If no valid username and password can be found then request->credentials will be null.
The username in
request->credentialsis trimmed of leading and trailing spaces, since" john.doe"is not desired. The password is not trimmed, since leading/trailing spaces are valid password characters per RFC 2617.
A colon (
:) is only treated as the username/password separator on its first occurrence. Any further colons belong to the password. For example, decoded credentials ofjohn:doe:passwordare parsed as Username:john, Password:doe:password. A:inside the username itself is not supported per the spec.
Example:
<?php
require_once("./classes/WebFramework.php");
$webFramework = new WebFramework();
$webFramework->parse_auth(); // activate parsing of Basic Authentication & Bearer tokens
$webFramework->get("/protected", function() use($webFramework) {
$credentials = $webFramework->request->credentials;
if($credentials === null) {
return $webFramework->send_json_body(array(
"status" => 403,
"message" => 'Missing or invalid Authorization header provided (use: "Authorization: Basic ...")!',
));
}
if(
$credentials["username"] !== "john.doe" &&
$credentials["password"] !== "password"
) {
return $webFramework->send_json_body(array(
"status" => 403,
"message" => 'Provided credentials are invalid!',
));
}
return $webFramework->send_json_body(array(
"status" => 200,
"message" => "Hello protected world!",
));
});
$webFramework->start();
?>You can easily customize the provided 404 response for any HTTP method by settings the route URI to: :404. Customization can be done on a per HTTP method way, or for all methods using all().
Custom 404's can also use the
render_html()andrender_view()methods for rendering more complex pages.
Examples:
<?php
// example #1: special "ALL" request handling (will handle GET, POST, PUT, etc.)
$this->all(":404", function() {
return $this->send("No route found!", 404);
});
// example #2: GET request handling
$this->get(":404", function() {
return $this->send_json_body(array(
"status" => 404,
"message" => "No route found!",
));
});
// example #3: POST request handling
$this->post(":404", function() {
return $this->send_json_body(array(
"status" => 404,
"message" => "No route found!",
));
});
?>You can easily customize the default error handler that is provided. This error handler will deal with fatal errors and exceptions.
Error handling can also be disabled in the constructor, e.g.
$webFramework = new WebFramework(array("handle_php_errors" => false));.
The
handle_php_errorsoption cannot be disabled if you want to use a custom error handler withset_custom_error_handler. Ifhandle_php_errorsis disabled then your custom error handler will never be called. Ifhandle_php_errorsis disabled you can still set a custom exception and error handler using native PHP.
Debug mode can be turned on to get more detailed error messages.
Example:
<?php
$webFramework = new WebFramework(array(
"debug_mode" => true // use this if you want more detailed messages (not recommended for production)
));
// must be called before start()
$webFramework->set_custom_error_handler(function(int $error_code, string $error_message) use($webFramework) {
return $webFramework->send_json_body(array(
"status" => 500,
"message" => "Something went wrong, please try again later",
"error" => array(
"code" => $error_code,
"message" => $error_message,
)
));
});
$webFramework->start();
?>You can send custom HTTP headers either for all routes or on a per route basis.
Example, all routes:
<?php
require_once("./classes/WebFramework.php");
// Example HTTP header (will be activated for all loaded routes)
header("Strict-Transport-Security: max-age=15552000; includeSubDomains");
$webFramework = new WebFramework();
// Custom headers can be set at any point until "$webFramework->start();"
$webFramework->start();
?>Example, one routes:
<?php
$this->get("/hello", function() {
// Example HTTP header (will be activated for this route only)
header("Strict-Transport-Security: max-age=15552000; includeSubDomains");
return $this->send_json_body(array(
"status" => 200,
"message" => "Hello world!",
));
});
?>This framework includes Helmet's (JS) defaults that can be activated by calling
$webFramework->helmet(), this must be called before$webFramework->start().
This can also be used on a per route basis, by calling it at the start of a route the same way that custom headers are added in the above section.
Since version
0.3.0helmet is included by default in every response. It can be disabled using thealways_use_helmetconstructor option.
Example:
<?php
require_once("./classes/WebFramework.php");
$webFramework = new WebFramework();
$webFramework->helmet(); // activate Helmet
$webFramework->start();
?>Implementing CORS handling is not something I feel is necessary. The point of this framework is to only provide what is necessary and potential security benefits. As such if you want to add CORS handling you can add it to all loaded routes by adding it above your call to start() or using a global middleware. Also since CORS can be handled in various ways, implementing it would be counter productive.
CORS handling can also be added on a per route basis. If this is done then it has to be added before
send(),send_json(),send_json_body(),send_file().
Example, all routes:
<?php
require_once("./classes/WebFramework.php");
// Simple example CORS headers (will be activated for all loaded routes)
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET,HEAD,PUT,PATCH,POST,DELETE");
$webFramework = new WebFramework();
// CORS headers can be set at any point until "$webFramework->start();"
$webFramework->start();
?>Example, one routes:
<?php
$this->get("/hello", function() {
// Simple example CORS headers (will be activated for this route only)
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET,HEAD,PUT,PATCH,POST,DELETE");
return $this->send_json_body(array(
"status" => 200,
"message" => "Hello world!",
));
});
?>