Utility Helpers
Small static functions the whole codebase leans on. Several exist because the PHP builtin they replace gives the wrong answer here.
Overview
Most of these wrap a PHP builtin that is wrong here. The raw function ignores the configured encoding, breaks on Turkish, or produces JSON the rest of the system cannot read back.
Everything below is static, and a failure is a falsy return. Only the request helper says why, in Utility::$error.
Reference
Calling a Remote Service
public static function HttpRequest($url = '', $params = [], $retry = 0);
// Preferred: one options array as the FIRST argument.
$body = Utility::HttpRequest([
'url' => 'https://api.example.com/v1/ping',
'type' => 'POST',
'data' => ['a' => 1],
'header' => ['Accept: application/json'],
]);
// Legacy: address first, a smaller options array second.
$body = Utility::HttpRequest('https://api.example.com/v1/ping', ['post' => ['a' => 1]]);
Returns the response body as a string, or false when the transfer failed. The third argument is the internal redirect counter, never passed by a caller. Options:
| Key | Type | Default | What it does |
|---|---|---|---|
url | string | required | Target address. A query string belongs here, not in data. |
type | string | GET | Method, uppercased. Anything but GET goes as a custom request. |
data | array or string | none | Request body. An array is form encoded; a string goes verbatim, which is how JSON is sent. Ignored on GET. |
header | array | empty | Whole header lines, for example 'Authorization: Bearer ...'. |
timeout | int | 30 | Seconds allowed for the whole transfer. |
connect_timeout | int | 10 | Seconds allowed for the connection phase alone. |
ssl_verify | bool | true | Verifies the peer and the host name. Turn off only against a service you control. |
allow_ipv6 | bool | false | While false, resolution is forced to v4; a host without v6 routing blocks until the system timeout. |
post, timeout (default 5), connect_timeout, ssl_verify (default false) and allow_ipv6. It sends no headers and switches to POST as soon as post is present.
false it carries the transport message, a name resolution failure for example. This method is its only writer, so a stale value survives every other failure. Read it before the next call overwrites it.
JSON
public static function jencode($string = '', $flags = 0): string|false;
public static function jdecode($string = '', $mode = false);
false for a value that cannot be encoded.
null.
Text
public static function strtoupper($str, $encode = 'utf8');
public static function strtolower($str, $encode = 'UTF-8');
public static function ucfirst($string, $encoding = 'utf8');
public static function strlen($str, $charset = 'utf-8');
public static function substr($str = '', $start = 0, $end = -1, $charset = 'utf-8');
public static function short_text($text = '', $start = false, $end = false, $points = false, $charset = 'UTF-8');
null to read to the end.
Addresses
public static function AppAdress($prefix = false);
public static function RequestURI();
public static function redirect($url = '', $time = 0): void;
public static function getReferer($internal_only = false);
public static function seo_url(string $url, array $allowed = ['page']): string;
public static function image_link_determiner($arg = '', $prefix = '', $rseparator = true);
null. Pass true to reject anything not from this installation.
The Visitor's Address
public static function resolve_client_ip(array $headers = []): string;
public static function trusted_proxies(): array;
public static function forwarded_header_ignored(): bool;
public static function ip_in_ranges(string $ip, array $ranges): bool;
public static function cidr_match(string $ip, string $cidr): bool;
Data and Files
public static function array_export($array = [], $options = []);
public static function xdecode($xml_string = '', $returnArray = false);
public static function array_to_xml(array $data, string $root = 'data'): string;
public static function generate_hash($length = 9, $add_dashes = false, $available_sets = 'luds');
public static function sizeFormat(int $bytes, string $emptyPlaceholder = "\u{2014}"): string;
pwith: true wraps the output as a complete file that returns the array, which is how configuration is saved. The result is evaluated first, and a stricter export replaces it if it does not come back as an array.
false. The root element becomes the single outer key.
l lowercase, u uppercase, d digits, s symbols; look-alike characters are excluded. The second groups the result with hyphens, which lengthens it.
Example
The call and the read back, together.
public function create_account(string $domain, string $plan): array
{
$body = Utility::jencode(['domain' => $domain, 'plan' => $plan]);
$response = Utility::HttpRequest([
'url' => 'https://api.example.com/v1/accounts',
'type' => 'POST',
'data' => $body, // a string is sent verbatim
'header' => [
'Authorization: Bearer ' . $this->config['token'],
'Content-Type: application/json',
],
'timeout' => 20,
]);
// Transport failure: nothing was parsed, the reason is on the class.
if ($response === false)
throw new Exception('Provider unreachable: ' . Utility::$error);
$result = Utility::jdecode((string) $response, true);
// Protocol failure: we got an answer, it is not the one we need.
if (!is_array($result) || !isset($result['id']))
throw new Exception('Unexpected response from the provider.');
return [
'id' => $result['id'],
'quota' => Utility::sizeFormat((int) ($result['quota_bytes'] ?? 0)),
];
}
Pitfalls
The legacy form turns certificate verification off and drops the transfer timeout from thirty seconds to five. Writing the address as the first argument out of habit disables verification silently. Use the options array.
When a location line appears in the body the call re-issues itself with that address and the legacy defaults. Method, body and headers are not carried over, so an authenticated POST comes back as an anonymous GET. Follow such a response yourself.
The Turkish letter mapping applies only while the active language is Turkish, so the same input uppercases differently in two sessions. Never build a stored key, a comparison key or a file name that way. Use it for what a person will read.
An element with text inside it drops its attributes entirely, and repeated siblings collapse into one key. A response with one item is a string; the same response with two is a list. Parse a provider whose answer depends on either yourself.
Related Articles
Vielen Dank für Ihre Rückmeldung!
Unser Support-Team ist rund um die Uhr für Sie da, wenn Sie oben nicht fündig werden.