🧰
PHP Essentials
A comprehensive zero-dependency PHP utility toolkit with 80+ helper methods for strings, arrays, dates, validation, security, HTTP, and file operations.
PHP
Utility
· v1.0.0
· 1 downloads
Download
Download PhpEssentials.php
(36.5 KB)
curl -OL https://ahmedhabib.com/libraries/download/php-essentials
7
Classes
80+
Methods
0
Dependencies
8.0+
PHP Version
require_once 'PhpEssentials.php';
String Manipulation
18 methods for slugs, case conversion, truncation, masking, and more
Str::slug($text, $separator)
Convert to a URL-friendly slug with Unicode transliteration.
Str::slug('Hello World!'); // "hello-world" Str::slug('Café Résumé'); // "cafe-resume"
Str::camel / pascal / snake / kebab
Convert between camelCase, PascalCase, snake_case, and kebab-case.
Str::camel('user_first_name'); // "userFirstName" Str::pascal('user name'); // "UserName" Str::snake('userName'); // "user_name" Str::kebab('userName'); // "user-name"
Str::truncate / truncateWords
Truncate by character limit or word count with customizable suffix.
Str::truncate('A very long text', 10); // "A very..." Str::truncateWords('The quick brown fox', 2); // "The quick..."
Str::contains / startsWith / endsWith
Check substrings with optional case-insensitive matching.
Str::contains('Hello World', 'world', true); // true (case-insensitive) Str::startsWith('/api/users', '/api'); // true
Str::mask($text, $char, $start, $end)
Mask sensitive data — emails, phones, card numbers, tokens.
Str::mask('[email protected]'); // "jo************om" Str::mask('4111222233334444', '*', 4, 4); // "4111********4444"
Str::between($text, $start, $end)
Extract text between two delimiters.
Str::between('Hello [world] foo', '[', ']'); // "world"
Str::random / wordCount / readingTime
Generate random strings, count words, estimate reading time.
Str::random(32); // "aB3xK9m..." Str::wordCount('Hi there'); // 2 Str::readingTime($article); // 5 (minutes)
Str::linkify / plainText / excerpt / nl2br
Convert URLs to links, strip HTML, generate excerpts.
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
Arr::get($array, $key, $default)
Access nested values using dot notation with a fallback default.
$cfg = ['db' => ['host' => 'localhost']]; Arr::get($cfg, 'db.host'); // "localhost" Arr::get($cfg, 'db.port', 3306); // 3306
Arr::set / has / forget
Set, check, or remove nested keys using dot notation.
Arr::set($cfg, 'db.port', 3306); Arr::has($cfg, 'db.port'); // true Arr::forget($cfg, 'db.port'); // removed
Arr::pluck($array, $key, $indexBy)
Extract a single column, optionally indexed by another key.
$users = [ ['id' => 1, 'name' => 'Alice'], ['id' => 2, 'name' => 'Bob'], ]; Arr::pluck($users, 'name'); // ["Alice", "Bob"] Arr::pluck($users, 'name', 'id'); // [1 => "Alice", 2 => "Bob"]
Arr::groupBy($array, $key)
Group items by a shared key value into sub-arrays.
$items = [ ['type' => 'fruit', 'name' => 'Apple'], ['type' => 'veg', 'name' => 'Carrot'], ]; Arr::groupBy($items, 'type'); // ["fruit" => [...], "veg" => [...]]
Arr::only / except
Whitelist or blacklist specific array keys.
$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 / sortBy / where / uniqueBy
Flatten nested arrays, sort/filter/deduplicate by key.
Arr::flatten([[1, [2]], [3]]); // [1, 2, 3] Arr::sortBy($users, 'name', 'desc'); Arr::where($users, 'role', 'admin'); Arr::uniqueBy($users, 'email');
Arr::first / last
Get the first or last element matching a callback.
Arr::first($users, fn($u) => $u['age'] > 18); Arr::last($users); // last element
Arr::paginate($array, $perPage, $page)
Paginate an array with full metadata: total, pages, has_next, etc.
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($date)
Human-readable relative time string.
Date::ago('2025-12-30 10:00:00'); // "2mo ago" Date::ago(new DateTime('-5 minutes')); // "5m ago"
Date::diff($from, $to, $unit)
Get difference in seconds, minutes, hours, days, weeks, months, or years.
Date::diff('2025-01-01', '2025-03-15', 'days'); // 73 Date::diff('2020-01-01', '2025-06-01', 'months'); // 65
Date::range($from, $to, $step, $format)
Generate an array of dates between two endpoints.
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 / isWeekend / age
Validate date strings, check weekends, calculate age from birthdate.
Date::isValid('2025-02-29'); // false Date::isWeekend('2025-03-01'); // true (Sat) Date::age('1990-05-15'); // 35
Date::format / startOfDay / endOfDay / fromNow
Format dates, get day boundaries, or show time until a future date.
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 / url / ip / ipv4 / ipv6
Validate common network formats using PHP filter functions.
Validate::email('[email protected]'); // true Validate::url('https://x.com'); // true Validate::ip('192.168.1.1'); // true Validate::ipv6('::1'); // true
Validate::password($pass, ...options)
Returns an array of validation errors (empty array = valid).
Validate::password('weak'); // ["Must be at least 8 characters", // "Must contain an uppercase letter"] Validate::password('Strong1Pass'); // [] ← empty = valid
Validate::creditCard($number)
Validate credit card numbers using the Luhn algorithm.
Validate::creditCard('4111111111111111'); // true (valid Luhn) Validate::creditCard('1234567890'); // false
Validate::between / length / regex / json
Check numeric ranges, string lengths, regex patterns, and JSON validity.
Validate::between(5, 1, 10); // true Validate::length('hello', 2, 10); // true Validate::regex('abc123', '/^\w+$/'); // true Validate::json('{"a":1}'); // true
Validate::hexColor / phone / slug / date
Validate colors, phone numbers, URL slugs, and date strings.
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
Secure::hashPassword / verifyPassword
Argon2ID password hashing with automatic bcrypt fallback.
$hash = Secure::hashPassword('myPassword'); Secure::verifyPassword('myPassword', $hash); // true Secure::needsRehash($oldHash); // true if algo/cost changed
Secure::encrypt / decrypt
AES-256-GCM authenticated encryption — tamper-proof.
$enc = Secure::encrypt('secret', 'key'); $plain = Secure::decrypt($enc, 'key'); // "secret"
Secure::token / uuid
Cryptographically secure random hex tokens and UUID v4.
Secure::token(32); // "a1b2c3d4e5...64 hex chars" Secure::uuid(); // "550e8400-e29b-41d4-a716-446655440000"
Secure::sign / verifySignature
HMAC-SHA256 signing for webhooks, API tokens, and data integrity.
$sig = Secure::sign('payload', 'secret'); Secure::verifySignature('payload', $sig, 'secret'); // true
Secure::csrfToken / escape / sanitizeFilename
CSRF protection, XSS-safe HTML escaping, and directory traversal prevention.
$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
Http::get / post / put / delete
Full cURL HTTP client with JSON decoding and header parsing.
$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($base, $params)
Build a URL with properly encoded query parameters.
Http::buildUrl('https://api.example.com/search', [ 'q' => 'php essentials', 'page' => 2, ]); // ".../search?q=php+essentials&page=2"
Http::clientIp / isAjax
Get client IP (proxy-aware: CF, X-Forwarded-For) and detect AJAX.
Http::clientIp(); // "203.0.113.42" Http::isAjax(); // true if X-Requested-With header set
Http::json / redirect
Send a JSON response or redirect — both exit immediately.
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::read / write / append / delete
Core file operations with automatic directory creation.
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 / extension / mimeType / exists
Human-readable file sizes, extensions, MIME types, and existence checks.
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::readJson / writeJson
Read and write JSON files in a single call with pretty printing.
File::writeJson('/tmp/config.json', [ 'debug' => false, 'version' => '1.0.0', ]); $cfg = File::readJson('/tmp/config.json'); // ["debug" => false, "version" => "1.0.0"]
File::readCsv($path, $delimiter)
Parse CSV files into associative arrays using the header row as keys.
// users.csv: name,email // Alice,[email protected] File::readCsv('users.csv'); // [["name"=>"Alice", "email"=>"[email protected]"]]
File::list / listRecursive / copy / move
List files with glob patterns, recursively search, copy and move.
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');
About This Library
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.
How to Use
- Download PhpEssentials.php
- Include or autoload it in your project
- Use the static helper classes: Str::, Arr::, Date::, Validate::, Secure::, Http::, File::