PHP Essentials
A comprehensive zero-dependency PHP utility toolkit with 80+ helper methods for strings, arrays, dates, validation, security, HTTP, and file operations.
Download
curl -OL https://ahmedhabib.com/libraries/download/php-essentials
PHP Essentials is a single-file, zero-dependency utility library for PHP 8.0+ that provides a rich collection of static helper methods organized into logical categories: Str (string manipulation), Arr (array utilities), Date (date/time helpers), Validate (input validation), Secure (security & hashing), Http (HTTP request helpers), and File (filesystem operations). Drop it into any project and start using it immediately.
Every PHP project needs the same foundational helpers — slug generation, input validation, date formatting, secure password hashing, file I/O, and more. Rather than pulling in heavyweight frameworks or stitching together dozens of micro-packages, PHP Essentials gives you 80+ battle-tested static methods in a single file with zero external dependencies. Designed for PHP 8.0+, it organizes helpers into seven intuitive classes that follow consistent naming conventions and return predictable types. Drop it into any project — from quick scripts to full MVC applications — and immediately start writing cleaner, safer code without managing Composer dependencies or framework lock-in.
-
Str 18 methods
String manipulation — slugify, camelCase, PascalCase, snake_case, kebab-case, truncate by chars or words, contains/startsWith/endsWith checks, mask sensitive data, extract between delimiters, random strings, word count, reading time estimation, linkify URLs, strip HTML, excerpts, and newline conversion.
-
Arr 16 methods
Array utilities — dot-notation get/set/has/forget for nested values, flatten multi-dimensional arrays, pluck columns, groupBy key, only/except key whitelisting, first/last with callbacks, where filtering, sortBy key, uniqueBy deduplication, paginate with metadata, and toMap for select dropdowns.
-
Date 10 methods
Date and time helpers — human-readable "time ago" and "from now" strings, flexible date formatting, date validation against formats, diff in any unit (seconds through years), weekend detection, start/end of day boundaries, date range generation with custom steps, and age calculation from birthdate.
-
Validate 14 methods
Input validation — email, URL, IP (v4/v6), numeric range checks, string length bounds, regex pattern matching, JSON validity, credit card numbers via Luhn algorithm, hex color codes, date format validation, password strength with configurable rules, phone numbers, and URL slug format.
-
Secure 12 methods
Security and cryptography — Argon2ID password hashing with bcrypt fallback, password verification and rehash detection, AES-256-GCM authenticated encryption/decryption, cryptographic hex tokens, UUID v4 generation, XSS-safe HTML escaping, CSRF token generation and verification, HMAC-SHA256 signing and verification, and filename sanitization against directory traversal.
-
Http 8 methods
HTTP requests and responses — full cURL client for GET/POST/PUT/DELETE with JSON decoding and header parsing, URL building with query parameters, proxy-aware client IP detection (CloudFlare, X-Forwarded-For), AJAX request detection, JSON response helper, and redirect helper — both exit immediately.
-
File 13 methods
Filesystem operations — read/write/append/delete with auto directory creation, file existence checks, human-readable file sizes, extension and MIME type detection, glob-based file listing, recursive directory search, copy and move with auto mkdir, JSON file read/write with pretty printing, and CSV parsing into associative arrays using header rows.
- Download PhpEssentials.php
- Include or autoload it in your project
- Use the static helper classes: Str::, Arr::, Date::, Validate::, Secure::, Http::, File::
require_once 'PhpEssentials.php';
String Manipulation
18 methods for slugs, case conversion, truncation, masking, and more
Str::slug('Hello World!'); // "hello-world" Str::slug('Café Résumé'); // "cafe-resume"
Str::camel('user_first_name'); // "userFirstName" Str::pascal('user name'); // "UserName" Str::snake('userName'); // "user_name" Str::kebab('userName'); // "user-name"
Str::truncate('A very long text', 10); // "A very..." Str::truncateWords('The quick brown fox', 2); // "The quick..."
Str::contains('Hello World', 'world', true); // true (case-insensitive) Str::startsWith('/api/users', '/api'); // true
Str::mask('[email protected]'); // "jo************om" Str::mask('4111222233334444', '*', 4, 4); // "4111********4444"
Str::between('Hello [world] foo', '[', ']'); // "world"
Str::random(32); // "aB3xK9m..." Str::wordCount('Hi there'); // 2 Str::readingTime($article); // 5 (minutes)
Str::linkify('Visit https://x.com'); // 'Visit <a href="...">...</a>' Str::excerpt($html, 20); // plain text words
Array Utilities
15 methods for dot notation, plucking, grouping, filtering, and pagination
$cfg = ['db' => ['host' => 'localhost']]; Arr::get($cfg, 'db.host'); // "localhost" Arr::get($cfg, 'db.port', 3306); // 3306
Arr::set($cfg, 'db.port', 3306); Arr::has($cfg, 'db.port'); // true Arr::forget($cfg, 'db.port'); // removed
$users = [ ['id' => 1, 'name' => 'Alice'], ['id' => 2, 'name' => 'Bob'], ]; Arr::pluck($users, 'name'); // ["Alice", "Bob"] Arr::pluck($users, 'name', 'id'); // [1 => "Alice", 2 => "Bob"]
$items = [ ['type' => 'fruit', 'name' => 'Apple'], ['type' => 'veg', 'name' => 'Carrot'], ]; Arr::groupBy($items, 'type'); // ["fruit" => [...], "veg" => [...]]
$d = ['name'=>'Jo', 'email'=>'[email protected]', 'pass'=>'s']; Arr::only($d, ['name', 'email']); // ["name" => "Jo", "email" => "[email protected]"] Arr::except($d, ['pass']); // ["name" => "Jo", "email" => "[email protected]"]
Arr::flatten([[1, [2]], [3]]); // [1, 2, 3] Arr::sortBy($users, 'name', 'desc'); Arr::where($users, 'role', 'admin'); Arr::uniqueBy($users, 'email');
Arr::first($users, fn($u) => $u['age'] > 18); Arr::last($users); // last element
Arr::paginate($items, 10, 2); // ["data" => [...], "total" => 50, // "current_page" => 2, "has_next" => true]
Date & Time Helpers
10 methods for relative time, diffs, ranges, validation, and formatting
Date::ago('2025-12-30 10:00:00'); // "2mo ago" Date::ago(new DateTime('-5 minutes')); // "5m ago"
Date::diff('2025-01-01', '2025-03-15', 'days'); // 73 Date::diff('2020-01-01', '2025-06-01', 'months'); // 65
Date::range('2025-01-01', '2025-01-05'); // ["2025-01-01", "2025-01-02", ...] Date::range('2025-01', '2025-06', '+1 month', 'Y-m'); // ["2025-01", "2025-02", ...]
Date::isValid('2025-02-29'); // false Date::isWeekend('2025-03-01'); // true (Sat) Date::age('1990-05-15'); // 35
Date::format('2025-03-15', 'F j, Y'); // "March 15, 2025" Date::startOfDay(); // "2025-03-03 00:00:00" Date::fromNow('2026-12-25'); // "in 42w"
Input Validation
14 methods for emails, passwords, credit cards, URLs, and more
Validate::email('[email protected]'); // true Validate::url('https://x.com'); // true Validate::ip('192.168.1.1'); // true Validate::ipv6('::1'); // true
Validate::password('weak'); // ["Must be at least 8 characters", // "Must contain an uppercase letter"] Validate::password('Strong1Pass'); // [] ← empty = valid
Validate::creditCard('4111111111111111'); // true (valid Luhn) Validate::creditCard('1234567890'); // false
Validate::between(5, 1, 10); // true Validate::length('hello', 2, 10); // true Validate::regex('abc123', '/^\w+$/'); // true Validate::json('{"a":1}'); // true
Validate::hexColor('#ff0'); // true Validate::phone('+1-555-1234'); // true Validate::slug('my-post-123'); // true Validate::date('2025-13-01'); // false
Security & Cryptography
12 methods for passwords, encryption, CSRF, tokens, and HMAC signing
$hash = Secure::hashPassword('myPassword'); Secure::verifyPassword('myPassword', $hash); // true Secure::needsRehash($oldHash); // true if algo/cost changed
$enc = Secure::encrypt('secret', 'key'); $plain = Secure::decrypt($enc, 'key'); // "secret"
Secure::token(32); // "a1b2c3d4e5...64 hex chars" Secure::uuid(); // "550e8400-e29b-41d4-a716-446655440000"
$sig = Secure::sign('payload', 'secret'); Secure::verifySignature('payload', $sig, 'secret'); // true
$token = Secure::csrfToken(); Secure::verifyCsrf($_POST['token']); // bool Secure::escape('<script>x</script>'); // safe HTML entity output Secure::sanitizeFilename('../../etc/passwd'); // "passwd"
HTTP Requests & Responses
8 methods for cURL requests, URL building, IP detection, and JSON responses
$r = Http::get('https://api.example.com/users'); // $r['status'] → 200 // $r['json'] → decoded array // $r['headers'] → parsed headers $r = Http::post('https://api.example.com/users', [ 'name' => 'Alice', 'email' => '[email protected]', ], ['Authorization: Bearer tok']);
Http::buildUrl('https://api.example.com/search', [ 'q' => 'php essentials', 'page' => 2, ]); // ".../search?q=php+essentials&page=2"
Http::clientIp(); // "203.0.113.42" Http::isAjax(); // true if X-Requested-With header set
Http::json(['success' => true], 200); // Sends JSON + exits Http::redirect('/dashboard', 302); // 302 redirect + exits
Filesystem Operations
13 methods for reading, writing, listing, copying, and parsing files
File::write('/tmp/data/log.txt', 'Hello'); // Creates /tmp/data/ if needed $content = File::read('/tmp/data/log.txt'); // "Hello" (or null if missing) File::append('/tmp/data/log.txt', "\nWorld"); File::delete('/tmp/data/log.txt');
File::size('/var/log/app.log'); // "2.34 MB" File::extension('photo.JPG'); // "jpg" File::mimeType('photo.jpg'); // "image/jpeg" File::exists('/tmp/data.txt'); // true/false
File::writeJson('/tmp/config.json', [ 'debug' => false, 'version' => '1.0.0', ]); $cfg = File::readJson('/tmp/config.json'); // ["debug" => false, "version" => "1.0.0"]
// users.csv: name,email // Alice,[email protected] File::readCsv('users.csv'); // [["name"=>"Alice", "email"=>"[email protected]"]]
File::list('/var/uploads', '*.jpg'); // ["/var/uploads/photo1.jpg", ...] File::listRecursive('/app/src', '*.php'); // all PHP files recursively File::copy('a.txt', 'backup/a.txt'); File::move('old.txt', 'archive/old.txt');