aranxo / basics
Standalone static helper classes for arrays, strings, dates, file names, file system, domain names, networking, sessions, cookies, configuration and environment initialization.
Requires
- php: >=8.1
- ext-gmp: *
- ext-iconv: *
- ext-intl: *
- ext-json: *
- ext-mbstring: *
Requires (Dev)
- phpstan/phpstan: ^2.1
- phpunit/phpunit: ^10.5 || ^11.5
Suggests
- ext-curl: Required for NetInfo::urlExists()
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-11-19 17:56:00 UTC
README
A set of standalone PHP helper classes for everyday tasks: arrays, strings, dates, file names, the file system, domain names, networking (IPv4/IPv6 CIDR and bogon handling), sessions, cookies, JSON configuration and environment initialization. Every class works on its own – there are no dependencies between the classes and no external Composer dependencies.
Installation
composer require aranxo/basics
Requirements
- PHP ≥ 8.1
- PHP extensions:
gmp(IPv6 calculations inNetInfo),intl(localized names inDateTimeExt),mbstring,iconv,json - No external Composer dependencies
- Optional: PHP extension
curlforNetInfo::urlExists()
Classes
All classes live in the namespace Aranxo\Basics.
| Class | Purpose (from the class docblock) |
|---|---|
Arrays |
Provides functions to manage arrays. All methods in this class are static |
Config (trait) |
Shared environment/config helpers for JSON-based configuration files |
Cookies |
A cookie management class |
DateTimeExt |
This class extends the PHP built in class DateTime with more functionality |
DomainNames |
Provides functions to work with domain names |
FileNames |
Provides functions to work with filenames |
FileSystem |
Provides functions to work with the file system. All methods in this class are static |
Initializer |
Provides functions to initialize some important informations about the environment, the transport protocol, set error handling, localization parameters and paths. All methods in this class are static |
NetInfo |
Collection of Internet related functions. All methods in this class are static |
Session |
A wrapper class for the session functions. All methods in this class are static |
Strings |
Provides functions to manage strings |
Arrays
| Method | Description |
|---|---|
countDim(array $array): int |
Counts the dimensions of an array |
isAssoc(array $array): bool |
Tests if an array is an associated array or array is not properly indexed |
isFilledArray($array): bool |
Tests if a value is a filled array |
deleteKey(array $array, $key): array |
Deletes an array item by the key |
deleteValue(array $array, $value): array |
Deletes an array item by the value |
deleteKeys(array $array, array $keys): array |
Deletes array items by their keys |
deleteValues(array $array, array $values): array |
Deletes array items by their values |
combineSafe(array $keys, array $values, bool $chopkeys = false, $filler = null): array |
Enhancement to the function array_combine, where both arrays must have the same size, otherwise you will get false as return value. This function can handle different sizes |
findIndex(array $array, $pos, $text, $bigger = false): mixed |
Searches in a two dimensional array in a certain column for a matching text |
sortByColumns(array $array, array $columns): array |
Sorts a two-dimensional array by one or more columns |
swapDimensions(array $array): array |
Swaps the row keys with the column keys and vice versa |
flatten(array $array, string $separator = '_'): array |
Flattens a multidimensional array to an onedimesional associative array |
printFormatted(array $array): string |
Gives back the keys and values of an associative array in a formatted way |
Config (trait)
Protected helpers intended to be used inside your own classes.
| Method | Description |
|---|---|
isLocal(): bool |
Determines if we are in a local test environment |
getEnvironment(): string |
Determines the name of the environment to use |
loadConfig(?string $jsonfile = null): void |
Loads class-specific JSON config values for the current environment |
getConfigBasePath(): string |
Returns the base path where class-specific config JSON files are stored. Defaults to the "data" folder of this package; override in the using class to point to another location |
Cookies
| Method | Description |
|---|---|
__construct() |
The constructor |
setExpires($expires): self |
Sets the expiration date |
setPath(string $path): self |
Sets the default path |
setDomain(string $domain): self |
Sets the default domain |
setOption(string $option, $value): self |
Sets a option |
set(string $name, string $value, $expires = null): bool |
Set the cookie |
setMulti(array $array): self |
Sets multiple cookies |
exists(string $name): bool |
Checks if cookie is set |
get(string $name, string $default = ''): string |
Gets the cookie value |
getMulti(array $keys, $default = ''): array |
Get multiple values from cookies |
delete(string $name): void |
Deletes a cookie |
deleteMulti(array $keys): void |
Deletes multiple cookies |
DateTimeExt
Extends \DateTime. Constants: MYSQL (Y-m-d H:i:s), GERMAN_MINUTES
(d.m.Y H:i), GERMAN_SECONDS (d.m.Y H:i:s).
| Method | Description |
|---|---|
__construct($datetime = 'now', ?\DateTimeZone $timezone = null) |
The constructor |
__toString() |
Return Date in MYSQL format |
addYears(int $years): self |
Add years to a date |
addMonths(int $months): self |
Add months to a date |
addDays(int $days): self |
Add days to a date |
addHours(int $hours): self |
Add hours to a date |
addMinutes(int $minutes): self |
Add minutes to a date |
addSeconds(int $seconds): self |
Add seconds to a date |
diffInYears($at = 'now'): int |
Gives the difference to a second date in years |
diffInMonths($at = 'now'): int |
Gives the difference to a second date in months |
diffInDays($at = 'now'): int |
Gives the difference to a second date in days |
diffInHours($at = 'now'): int |
Gives the difference to a second date in hours |
diffInMinutes($at = 'now'): int |
Gives the difference to a second date in minutes |
diffInSeconds($at = 'now'): int |
Gives the difference to a second date in seconds |
age(): int |
Return Age in Years (quite an alias for diffInYears) |
lastOfMonth(): int |
Returns the last day of this month |
weekdayName(): string |
Returns the localized name of the weekday |
monthName(): string |
Returns the localized name of the month |
toMysql() |
Gets the date stored in this FeedDate as a MySQL date |
toRfc822() |
Gets the date stored in this FeedDate as an RFC 822 date |
toIso8601() |
Gets the date stored in this FeedDate as an ISO 8601 date |
toAtom() |
Gets the date stored in this FeedDate as an ATOM/RFC 3339 date |
toRfc1123() |
Gets the date stored in this FeedDate as an RFC 1123 date |
toRfc7231() |
Gets the date stored in this FeedDate as an RFC 7231 date |
static create($datetime = 'now', string $timezone = ''): DateTimeExt |
Static function to create a DateTimeExt object by a value |
static now(string $timezone = ''): DateTimeExt |
Returns the current date and time as a DateTimeExt object |
static today(string $timezone = ''): DateTimeExt |
Returns the current date (not time) as a DateTimeExt object |
static getDefaultTimezone(): \DateTimeZone |
Returns the default timezone set before by date_default_timezone_set |
static currentYear(): int |
Returns the current year |
static isTimeZoneInCountry(string $timezone, string $country): bool |
Determines if a time zone is in the specified country |
DomainNames
| Method | Description |
|---|---|
normalizeDomain(string $domain): ?string |
Normalizes a domain name by removing schemes, user info, ports, and "www." prefix, and converting to ASCII |
removeDotSegments(string $path): string |
Removes "." and ".." segments from a URL path (RFC 3986, section 5.2.4) |
resolveUrl(string $href, string $base): string |
Resolves a possibly relative URL reference against an absolute base URL |
getOrigin(string $url): string |
Gets the origin (scheme + host + port) of a URL |
fromMailAddress(string $mailAddress): string |
Gets the domain from a mail address |
FileNames
| Method | Description |
|---|---|
directory(string $filename): string |
Gives back the directory of a files complete path |
basename(string $filename): string |
Gives back the basename of a files complete path |
filename(string $filename): string |
Gives back the filename without extension of a files complete path |
extension(string $filename): string |
Gives back the extension of a files complete path |
changeExtension(string $filename, string $ext): string |
Changes the extension of a file |
normalizePath(string $path): string |
Converts from Windows to Unix paths and replaces multiple slashes ("//") |
rootify(string $path): string |
Adds DOCUMENT_ROOT in front of a path if not present |
derootify(string $path): string |
Deletes DOCUMENT_ROOT in front of a path if present |
FileSystem
| Method | Description |
|---|---|
isEmptyFolder(string $dir): bool |
Checks if a folder exists but is empty |
delete(string $filename): bool |
Deletes a file in safe mode |
deleteFiles(string $dir, string $pattern = '*'): bool |
Deletes all files in a folder matching as certain pattern |
getNewestFile(string $dir, string $pattern = '*'): string |
Finds the newest file matching a pattern in a given folder |
getOldestFile(string $dir, string $pattern = '*'): string |
Finds the oldest file matching a pattern in a given folder |
clearDirectory(string $dir, int $timestamp): void |
Deletes all files in a folder that are older than the specified timestamp |
fileExists(string $filename): bool |
Tests if a file exists with absolute path or relative to the include paths |
harvestFilesFilter(string $dir, string $filter = '', bool $recursive = false): array |
Searches for all files in a certain directory which match to a certain pattern and returns them as array |
harvestFiles(string $dir, bool $recursive = false): array |
Searches for all files in a certain directory and returns them as array |
harvestFilesExtensions(string $dir, array $extensions, bool $recursive = false): array |
Searches for all files in a certain directory which have one of the given extensions and returns them as array |
harvestSubDirs(string $dir, bool $recursive = false): array |
Searches for all subfolders in a certain directory and returns them as array |
emptyDirectory(string $dir, string $pattern = '*'): bool |
Empties a directory complete with subfolders |
deleteDirectory(string $dir, string $pattern = '*'): bool |
Deletes a directory complete with subfolders |
moveDirectory(string $from, string $to, bool $recursive = false): bool |
Moves files from one directory to another |
copyDirectory(string $from, string $to, bool $recursive = false): bool |
Copies files from one directory to another |
createDirectory(string $dir, int $mode = 0777): bool |
Creates a new directory if not exists |
calcBytes($value): int |
Calculates the real bytes as integer from a short size description like 30M, 5K, 2G etc. |
createRandomFile(string $filename, $size): void |
Creates a random file of a specific size |
fileReplace(string $filename, array $replacements): void |
Replaces one or more parts with another part in a file |
Initializer
| Method | Description |
|---|---|
init(): void |
Initializes global error reporting and include paths |
setErrorLog(string $filename, bool $inTest = false): void |
Sets the error log filename |
addPaths(array $newpaths): void |
Adds paths to the include paths |
isTest(): bool |
Returns the indicator for the test environment |
isProduction(): bool |
Returns the indicator for the production environment |
isSSL(): bool |
Returns the indicator for the transport protocol |
isWindows(): bool |
Returns the indicator for the Windows operating system |
isUnix(): bool |
Returns the indicator for the Unix operating system |
isCLI(): bool |
Returns the indicator for the CLI environment |
getProtocol(): string |
Returns the correct protocol according to the SSL status |
getDomain(): string |
Returns the correct domain according to the SSL status |
NetInfo
| Method | Description |
|---|---|
createIPv4Regex(array $cidrs): string |
Creates a regex pattern for matching a list of IPv4 CIDR ranges |
createIPv6Regex(array $cidrs): string |
Creates a regex pattern for matching a list of IPv6 CIDR ranges |
ipRangeIPv4(string $cidr): array |
Checks a given IPv4 CIDR notation and gives back the lower and upper border of the matching IP range as two element array |
ipRangeIPv6(string $cidr): array |
Checks a given IPv6 CIDR notation and gives back the lower and upper border of the matching IP range as two element array |
ipRange(string $cidr): array |
Checks a given CIDR notation and gives back the lower and upper border of the matching IP range as two element array |
getAllIPv4sInCIDR(string $cidr): array |
Returns all IPv4 addresses contained in a given CIDR range as array |
getAllIPv6sInCIDR(string $cidr): array |
Returns all IPv6 addresses contained in a given CIDR range as array |
getAllIPsInCIDR(string $cidr): array |
Returns all IP addresses contained in a given CIDR range as array |
calcIPv4CIDR(array $ips): string |
Calculates the IPv4 CIDR notation which matches all IPv4s in a given array |
calcIPv6CIDR(array $ips): string |
Calculates the IPv6 CIDR notation which matches all IPv6s in a given array |
calcCIDR(array $ips): string |
Calculates the CIDR notation which matches all IPs in a given array |
intersectIPv4CIDRs(string $cidr1, string $cidr2): bool |
Calculates if an IPv4 is a member of a CIDR or one of two CIDRs is a subset of the other |
intersectIPv6CIDRs(string $cidr1, string $cidr2): bool |
Calculates if an IPv6 is a member of a CIDR or one of two IPv6 CIDRs is a subset of the other |
intersectCIDRs(string $cidr1, string $cidr2): bool |
Calculates if an IP is a member of a CIDR or one of two CIDRs is a subset of the other |
isBogonIPv4(string $cidr): bool |
Checks if a given IPv4 or IPv4 CIDR is a bogon |
isBogonIPv6(string $cidr): bool |
Checks if a given IPv6 or IPv6 CIDR is a bogon |
isBogonIP(string $cidr): bool |
Checks if a given IP or CIDR is a bogon |
getBogonIPv4CIDRs(): array |
Gets all bogon IPv4 CIDR ranges |
getBogonIPv6CIDRs(): array |
Gets all bogon IPv6 CIDR ranges |
getBogonCIDRs(): array |
Gets all bogon CIDR ranges (IPv4 and IPv6 combined) |
loadAllowedCIDRList(string $iplist): array |
Loads the allowed CIDRs from a JSON file |
loadAllowedAgentsList(string $iplist): array |
Loads the allowed agents from a JSON file |
getRealIP(): string |
Evaluates the real IP address of the current user |
urlExists(string $url): bool |
Checks if a given url really exists and is reachable |
Session
| Method | Description |
|---|---|
setPath(string $path, bool $absolute = false): void |
Sets the initial include paths and the session save path |
start(array $moreoptions = [], string $sessionname = ''): void |
Starts the session with session_start() |
hasStarted(): bool |
Tests if a session was started |
exists(string $name): bool |
Tests if a session variable exists |
set(string $name, $value): void |
Sets a session variable |
get(string $name) |
Gets a session variable |
delete(string $name): void |
Deletes a session variable |
hideGet() |
Hides the GET variables in the session, redirects to the same script without GET parameters and then pulls out the GET parameters from the session |
collectGarbage(): void |
Executes GarbageCollection immediately |
destroy(): void |
Destroys the session and related variables |
Strings
| Method | Description |
|---|---|
left(string $text, int $length): string |
Returns the left part of a string |
right(string $text, int $length): string |
Returns the right part of a string |
contains(string $text, string $part, $encoding = null): bool |
Tests if a string contains another string |
startsWith(string $text, string $part): bool |
Tests if a string starts with another string |
endsWith(string $text, string $part): bool |
Tests if a string ends with another string |
removeStart(string $text, string $part): string |
Removes a part from the start of a string if it matches |
removeEnd(string $text, string $part): string |
Removes a part from the end of a string if it matches |
beforeFirst(string $text, string $delimiter): string |
Gets the part of a string before first occurence of a certain delimiter |
afterFirst(string $text, string $delimiter): string |
Gets the part of a string after last occurence of a certain delimiter |
beforeLast(string $text, string $delimiter): string |
Gets the part of a string before last occurence of a certain delimiter |
afterLast(string $text, string $delimiter): string |
Gets the part of a string after last occurence of a certain delimiter |
findBetween(string $text, string $start, string $end, bool $reverse = false): string |
Gets the part of a string between two defined parts |
generateRandomString(int $length = 10): string |
Generates a random string of a certain length with numbers, upper and lower chars |
isUrl(string $url): bool |
Tests if a string is a url |
utf8Encode(string $text): string |
Encodes a string from ISO-8859-1 to UTF-8 |
htmlDecodeAll(string $text): string |
Decodes a string from HTML entities to UTF-8 |
Usage
<?php require 'vendor/autoload.php'; use Aranxo\Basics\Arrays; use Aranxo\Basics\DateTimeExt; use Aranxo\Basics\NetInfo; use Aranxo\Basics\Strings; echo Strings::beforeLast('archive.tar.gz', '.'), PHP_EOL; // archive.tar echo DateTimeExt::create('2024-02-29')->addYears(1)->toMysql(), PHP_EOL; // 2025-03-01 00:00:00 echo NetInfo::calcCIDR(['64.15.129.100', '64.15.129.126']), PHP_EOL; // 64.15.129.96/27 echo Arrays::printFormatted(['a' => 1, 'b' => 2]), PHP_EOL;
Testing & static analysis
composer install composer test # PHPUnit composer analyse # PHPStan, level 8
License
MIT – see LICENSE.