List of modules and their methods:
Attach a route to a page
$path = "/login";
$controller = "html/login.php";
TinyPHP::RegisterRoute($path, $controller);
You can specify dynamic route params in the URL (e.g. :groupid).
TinyPHP::RegisterRoute("/groups/:groupid/categories", "html/categories.php");
Gets the route param "groupid" from the URL.
TinyPHP::GetRouteParam("groupid");
Specifies the root path common to all routes. That's to avoid specifying the common path over and over on all RegisterRoute()
calls.
$rootPath = "/demo";
TinyPHP::RegisterRoot($rootPath);
Register the special 404 not found controller.
$notFoundController = "/html/404.php";
TinyPHP::Register404($notFoundController);
Register the special 500 internal error page.
$internalErrorController = "/html/500.php";
TinyPHP::Register500($internalErrorController);
Display the pre-registered 500 internal error page.
$msg = "My error message";
TinyPHP::ThrowError500($msg);
Register the special maintenance page (visible to any client trying to request any route).
$maintenanceController = "/html/maintenance.php";
TinyPHP::RegisterMaintenance($maintenanceController);
Activate maintenance mode. The specified IP address will be exempted from maintenance mode, allowing normal access to the website. Typically, this would be the IP address of the client conducting maintenance on the website.
$allowedIPAddress = "192.168.1.100";
TinyPHP::EnableMaintenance($allowedIPAddress);
Serves the incoming client request. This method should be called last, after all the route registration and modules initialization has been done.
TinyPHP::Run();
Return 200 and an optional custom payload:
$res = ["result" => "success"];
API::Ok($res);
Return an HTTP error code and a custom message:
API::Error(500, "message");
Get a json payload sent by POST:
$post = API::Post();
echo $post->userid;
echo $post->email;
Get the query parameters sent by GET:
$getParams = API::Get();
echo $getParams->userid;
echo $getParams->email;
Initialization:
function OnFieldNotFoundCallback($msg)
{
Api::Error(500, $msg);
}
Config::Init("configFile.json", OnFieldNotFoundCallback);
Get a configuration field:
$field = Config::GetField("myConfigField");
echo $field;
Get a random hex string:
$hex = Crypt::GetRandomHex(5);
echo $hex; // "0a56b"
Get a random UUID:
$uuid = Crypt::GetRandomUUID();
echo $uuid; // "d1577826-9ec4-4704-90db-c9240b441e86"
Encrypt a string using AES-256 (CTR mode). Returns a base64 cyphertext:
$cypherBase64 = Crypt::Encrypt("mymessage", "mykey");
Decrypt a base64 cyphertext using AES-256 (CTR mode). Returns the plain text message:
$plainBase64 = Crypt::Decrypt("mycyphertext", "mykey");
Manages currency values.
Initialization:
$format = "€ #,#";
$decimalDigits = 2;
Currency::Init($format, $decimalDigits);
Format an amount:
$amount = 1999;
$options = [
"format" => "€ #,#", // optional, if a different format is required
"fractDigits" => 2, // optional, fractional digits to display
];
$formattedAmount = Currency::Format($amount);
echo $formattedAmount; // "€ 19,99"
$amount = 1999;
$options = [
"fractDigits" => 1,
];
$formattedAmount = Currency::Format($amount);
echo $formattedAmount; // "€ 19,9"
Parse a currency value:
$raw = "19,99"
$value = Currency::Parse($raw);
echo $value; // 1999
All timestamps are represented as "Y-m-d H:i:s" strings.
Get current timestamp
$now = Date::Now();
echo $now; // "1982-05-19 21:30:45"
Format a timestamp using a specific format:
$timestamp = "1982-05-19 21:30:45";
$formattedDate = Date::Format($timestamp, "Y");
echo $formattedDate; // "1982"
Format a timestamp using the "Y-m-d" format:
$timestamp = "1982-05-19 21:30:45";
$formattedDate = Date::FormatYMD($timestamp);
echo $formattedDate; // "1982-05-19"
Format a timestamp using the "Y-m-d H:i:s" format:
$timestamp = "1982-05-19 21:30:45";
$formattedDate = Date::FormatYMDHis($timestamp);
echo $formattedDate; // "1982-05-19 21:30:45"
Parse a date in a custom format:
$date = "19 05 1982";
$timestamp = Date::Parse($date, "d m Y");
echo $timestamp; // "1982-05-19 21:30:45"
Parse a date in the "Y-m-d" format:
$date = "1982-05-19";
$timestamp = Date::ParseYMD($date);
echo $timestamp; // "1982-05-19 21:30:45"
Parse a date in the "Y-m-d H:i:s" format:
$date = "1982-05-19 21:30:45";
$timestamp = Date::ParseYMDHis($date);
echo $timestamp; // "1982-05-19 21:30:45"
Add days to a timestamp:
$timestamp = "1982-05-19 21:30:45";
$timestamp = Date::AddDays($timestamp, 2);
echo $timestamp; // "1982-05-21 21:30:45"
Add months to a timestamp:
$timestamp = "1982-05-19 21:30:45";
$timestamp = Date::AddMonths($timestamp, 2);
echo $timestamp; // "1982-07-19 21:30:45"
Add years to a timestamp:
$timestamp = "1982-05-19 21:30:45";
$timestamp = Date::AddYears($timestamp, 2);
echo $timestamp; // "1984-05-19 21:30:45"
Compute the numbers of days between two timestamps:
$timestamp1 = "1982-05-19 21:30:45";
$timestamp2 = "1982-05-21 21:30:45";
$diffDays = Date::DiffDays($timestamp1, $timestamp2);
echo $diffDays; // 2
Execute MySQL queries and get results.
Initialization:
function OnDbErrorCallback($msg)
{
Api::Error(500, $msg);
}
$config = (object)[
"host" => "myhost",
"user" => "myuser",
"pass" => "mypass",
"name" => "mydbname",
];
Db::Init($config, "OnDbErrorCallback");
Launch a query:
$res = Db::Query("SELECT * FROM users WHERE id = ? AND username = ?;", [123, "gianluca"]);
Initialization:
$config = (object)[
"default_language" => "it",
"languages": [
[
"lang" => "it",
"file" => "dictionaries/it.json"
],
[
"lang" => "en",
"file" => "dictionaries/en.json"
]
];
Dictionary::Init($config);
Dictionary example:
{
"404_TITLE": "404",
"404_BODY": "Page not found"
}
Translate a dictionary key:
$res = txt("404_BODY");
echo $res; // "Page not found"
Translate and echo a dictionary key:
etxt("404_BODY"); // "Page not found"
Set the language to a specific one. If not present in the language list, the default is used (see config object). If the language is not passed, it auto detects the client language.
Dictionary::SetLanguage("it");
Get the current set language
$lang = Dictionary::GetLanguage();
echo $lang; // "it"
Dictionary::SetLanguage();
Download a file to the browser.
Start the download:
$binaryContent = [binarydata];
Download::Start("myfile.pdf", "application/pdf", $binaryContent);
Sanitize user input, remove html tags:
$cleanMessage = Input::Clean($userMessage);
Log messages to file.
Initialization:
$logFolder = "/logs";
Logger::Init($logFolder);
Write a log line:
$sink = "LOGIN";
$message = "User logged in";
Logger::Write($sink, $message);
Generates QR-Codes.
Send the QR-Code to the browser as a PNG:
$qrcodedata = "test";
QRCodeGenerator::GetPng($qrcodedata);
Get the QR-Code as a GdImage object:
$qrcodedata = "test";
$image = QRCodeGenerator::GetImage($qrcodedata);
Get a file uploaded by the browser.
Is there a file being uploaded in the current POST request ?
$res = Upload::IsFileUploaded();
Get the file size in bytes:
$size = Upload::GetFileSize();
echo $size; // 1048576
Get the file extension:
$extension = Upload::GetFileExtension();
echo $extension; // "pdf"
Get the actual file:
$path = Upload::GetUploadedFilePath();
$fileContent = file_get_content($path);
Google Re-Captcha test.
Initialization:
$pubKey = "6Lf_GlQpAA.....";
$privKey = "6Lf_GlQpAA.....";
Captcha::Init($pubKey, $privKey);
This call injects the necessary JavaScript function to trigger the ReCAPTCHA test upon user interaction. Invoke the submitFormWithCaptchaCheck()
JavaScript function on form button click:
Captcha::InjectReCaptchaOnClick();
Server side verification:
$isHuman = Captcha::IsHuman($score = 0.5);
Send an email
Send an email:
$from = "[email protected]";
$fromname = "Gianluca";
$to = "[email protected]";
$subject = "Email subject";
$content = "Hello world!\nBye bye!";
$attachments = [
"cid1", "email_attachments/logo.jpg",
"cid2", "email_attachments/file.pdf",
];
$ccs = [
"[email protected]",
"[email protected]",
"[email protected]",
];
$isSent = Mail::Send(
$from,
$fromname,
$to,
$subject,
$content,
$attachments,
$ccs
);
For debugging purposes. All emails will be sent to the provided test email.
$testEmail = "[email protected]";
Mail::SetDebug($testEmail);
Set the email signature. The signature is appended automatically to all emails.
$signature = "My email signature";
Mail::SetEmailSignature($signature);
Read and write Excel/CSV files.
Load an Excel file:
$isLoaded = SpreadSheet::Load("my/spread/sheet.xlsx", null);
Load an CSV file:
$isLoaded = SpreadSheet::Load("my/spread/sheet.csv", ";"); // ";" = delimiter
Get total rows:
$totRows = SpreadSheet::GetTotRows();
Get total columns:
$totCols = SpreadSheet::GetTotCols();
Get a row. The row index is zero based (e.g. 0 = first row)
$rowIndex = 3;
$maxCellLength = 1000;
$totCols = SpreadSheet::GetRow($rowIndex, $maxCellLength);
Creates a CSV file and save it to disk:
$header = ["col1", "col2", "col3"];
$data = [
["a1", "b1", "c1"],
["a2", "b2", "c2"]
];
$separator = ";";
$dest = "my/spread/sheet.csv";
$isCreated = SpreadSheet::BuildCSVBinary($header, $data, $separator, $dest);
Creates a CSV file and returns it:
$header = ["col1", "col2", "col3"];
$data = [
["a1", "b1", "c1"],
["a2", "b2", "c2"]
];
$separator = ";";
$csvBinaryData = SpreadSheet::BuildCSVBinary($header, $data, $separator);
Creates an Excel file and save it to disk:
$header = ["col1", "col2", "col3"];
$data = [
["a1", "b1", "c1"],
["a2", "b2", "c2"]
];
$separator = ";";
$dest = "my/spread/sheet.xlsx";
$isCreated = SpreadSheet::BuildExcelBinary($header, $data, $separator, $dest);
Creates an Excel file and returns it:
$header = ["col1", "col2", "col3"];
$data = [
["a1", "b1", "c1"],
["a2", "b2", "c2"]
];
$separator = ";";
$excelBinaryData = SpreadSheet::BuildExcelBinary($header, $data, $separator);
Returns Excel mime type. Useful for sending the file to the browser as a download:
$mimeType = SpreadSheet::GetExcelMime();
Returns CSV mime type:
$mimeType = SpreadSheet::GetCSVMime();
Payment processor.
Initialization.
$config = (object)[
"phpSecretKey" => "sk_live_xxxxxxxxxxxxxxx",
"jsPublicKey" => "pk_live_xxxxxxxxxxxxxxx",
"endpointSecret" => "whsec_xxxxxxxxxxxxxxx",
"version" => "YYYY-MM-DD"
];
Stripe::Init($config);
Call Start()
at the earliest possibile moment in your checkout php page to bootstrap the Stripe payment process. Pass a custom purchase payload (eg. product name and quantity). The purchase payload will be sent by Stripe as-is to your payment webhook upon succesul payment.
$userMemail = "[email protected]";
$productName = "Product name shown on Stripe checkout page";
$description = "Product description shown on Stripe checkout page";
$imageUrl = "https://www.mywebsite.com/myproduct.png";
$price = 2099; // 20.99
$currency = "eur";
$successUrl = "https://www.mywebsite.com/paymentsuccess";
$cancelUrl = "https://www.mywebsite.com/paymentcancelled";
$purchasePayload = json_encode(["plan" => "PRO", "months" => 12]);
Stripe::Start(
$userEmail,
$productName,
$description,
$imageUrl,
$price,
$currency,
$successUrl,
$cancelUrl,
$purchasePayload
);
Call OutputJavaScript()
to make available the launchStripePaymentProcess
JavaScript function, used to open the Stripe payment page on the client browser.
PHP side:
Stripe::OutputJavaScript();
Javascript side:
$("#buy_button").on("click", () => {
launchStripePaymentProcess();
});
Call ProcessWebHook()
on your Stripe webhook to process the response from Stripe. paymentSuccessCallback
is called with the transaction id, user email and the purchase payload specified in Start()
. The method reacts to the checkout.session.completed
event only (payment successful).
function paymentSuccessCallback($transactionId, $userEmail, $purchasePayload)
{
// payment was successful, do your stuff here (unlock features etc..)
}
Stripe::ProcessWebHook($paymentSuccessCallback);
Authentication. This module provides a simple authentication system using cookie-based or token-based authentication. It allows for user login, session management, and user information retrieval.
This module utilizes plugins to handle user and session management. These plugins implement specific interfaces that define the required methods for interacting with user data and sessions. Here are the details of each plugin.
The database implementation for the plugins are already provided buy the module (AuthPluginDbUser
and AuthPluginDbSession
).
$options = (object)[
"tableName" => "customers",
"userIdFieldName" => "email",
"usernameFieldName" => "email",
"passwordFieldName" => "password"
];
$userPlugin = new AuthPluginDbUser();
$userPlugin->Init($options);
If needed, it's also possible to redefine the password check algorithm:
$options = (object)[
"tableName" => "customers",
"userIdFieldName" => "email",
"usernameFieldName" => "email",
"passwordFieldName" => "password"
];
function CustomPasswordCheckFunction($password, $storedPassword)
{
return sha1($password) == $storedPassword;
}
$userPlugin = new AuthPluginDbUser();
$userPlugin->Init($options, "CustomPasswordCheckFunction");
$options = (object)[
"tableName" => "sessions",
"sessionIdFieldName" => "sessionid",
"tokenFieldName" => "token"
];
$sessionPlugin = new AuthPluginDbSession();
$sessionPlugin->Init($options);
If you need to use a different database or authentication mechanism, you can create custom plugins by implementing the respective interfaces with your custom behavior.
Here's the interface for the two plugins:
interface AuthUserInterface {
public function Login($username, $password); // returns token on success, false on failure/denied
public function GetUserId($username); // returns the user id
public function GetUserInfo($id); // returns the user object
}
interface AuthSessionInterface {
public function AddSession($id, $token);
public function DeleteSessions($id); // if id is not specified, delete all session of current user
public function DeleteSession($token);
public function GetSessionId($token); // returns the session id
public function TruncateSessions(); // delete all sessions of all users
}
Initialize the authentication module.
Using cookie:
$options = (object)[
"method" => "cookie",
"cookieName" => "my-cookie-name"
];
Auth::Init($options, $userPlugin);
Using x-auth token:
$options = (object)[
"method": "xauth"
];
Auth::Init($options, $userPlugin);
Registers a session plugin into the Auth module.
$pluginName = "customers";
Auth::AddSessionPlugin($pluginName, $sessionCustomersPlugin);
The AddSessionPlugin
method enables the registration of multiple session plugins, allowing for seamless switching between different entities on the fly, such as users and customers.
Use a specific session plugin.
Auth::SetSessionPlugin("customers");
Authenticate the user. Returns false
if unsuccessful, returns a sessionToken if successful (and set the cookie, if method is cookie
)
$username = "username";
$password = "password";
$sessionToken = Auth::Login($username, $password);
Logout all current logged in clients belonging to the user.
Auth::LogoutAllSessions();
Logout the current client.
Auth::LogoutThisSession();
Is the user logged ?
$isLogged = Auth::IsLogged($config);
Get the current logged in user data.
$user = Auth::GetLoggedUserInfo();
Set a new password for the current user
$newPassword = "myNewPassword";
Auth::SetNewPassword($newPassword);
Delete all sessions of all users
Auth::TruncateSessions();