PHP Miscellaneous

Useful PHP functions and utilities

🔧 What are PHP Misc Functions?

PHP miscellaneous functions include utilities for system information, connection handling, constants, sleep delays, and unique identifiers. These functions help with debugging, performance optimization, and special programming tasks.


<?php
// Get PHP version
echo "PHP Version: " . phpversion();
echo "\n";
// Generate unique ID
echo "Unique ID: " . uniqid();
?>
                                    

Output:

PHP Version: 8.2.0
Unique ID: 65a1b2c3d4e5f

Misc Function Categories

â„šī¸

System Info

Get PHP and server details

phpversion() phpinfo() php_uname()
🆔

Unique IDs

Generate unique identifiers

uniqid() bin2hex() random_bytes()
âąī¸

Timing

Control script execution

sleep() usleep() time_sleep_until()
🔌

Connection

Manage script connections

connection_status() ignore_user_abort() connection_aborted()

🔹 System Information Functions

Retrieve information about your PHP installation, server environment, and operating system. These functions are useful for debugging and compatibility checks.

<?php
// PHP version
echo "PHP Version: " . phpversion() . "\n";
echo "PHP Major Version: " . PHP_MAJOR_VERSION . "\n";
echo "PHP Minor Version: " . PHP_MINOR_VERSION . "\n\n";

// Operating system info
echo "OS: " . php_uname('s') . "\n";
echo "Hostname: " . php_uname('n') . "\n";
echo "OS Version: " . php_uname('r') . "\n\n";

// Check if extension is loaded
echo "JSON extension: " . (extension_loaded('json') ? "Loaded" : "Not loaded") . "\n";
echo "MySQL extension: " . (extension_loaded('mysqli') ? "Loaded" : "Not loaded");
?>

Output:

PHP Version: 8.2.0
PHP Major Version: 8
PHP Minor Version: 2

OS: Linux
Hostname: webserver
OS Version: 5.15.0

JSON extension: Loaded
MySQL extension: Loaded

🔹 Generating Unique IDs

Create unique identifiers for database records, session tokens, file names, and temporary data. PHP offers several methods with different levels of uniqueness.

<?php
// Basic unique ID (based on time)
echo "uniqid(): " . uniqid() . "\n";

// Unique ID with prefix
echo "uniqid('user_'): " . uniqid('user_') . "\n";

// More unique (with more entropy)
echo "uniqid('', true): " . uniqid('', true) . "\n\n";

// Random bytes (cryptographically secure)
$bytes = random_bytes(16);
echo "Random hex: " . bin2hex($bytes) . "\n\n";

// UUID-like identifier
function generateUUID() {
    $data = random_bytes(16);
    $data[6] = chr(ord($data[6]) & 0x0f | 0x40);
    $data[8] = chr(ord($data[8]) & 0x3f | 0x80);
    return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}
echo "UUID: " . generateUUID();
?>

Output:

uniqid(): 65a1b2c3d4e5f
uniqid('user_'): user_65a1b2c3d5012
uniqid('', true): 65a1b2c3d5123.45678901

Random hex: 3f7a9b2c8e1d4f6a5b3c9e7d2f1a8b4c

UUID: 550e8400-e29b-41d4-a716-446655440000

🔹 Sleep and Delay Functions

Pause script execution for a specified time. Use sleep() for seconds, usleep() for microseconds, or time_sleep_until() to sleep until a specific timestamp.

<?php
echo "Start: " . date('H:i:s') . "\n";

// Sleep for 2 seconds
sleep(2);
echo "After 2 seconds: " . date('H:i:s') . "\n";

// Sleep for 500,000 microseconds (0.5 seconds)
usleep(500000);
echo "After 0.5 more seconds: " . date('H:i:s') . "\n\n";

// Sleep until specific time
$wake_time = time() + 1;
echo "Sleeping until: " . date('H:i:s', $wake_time) . "\n";
time_sleep_until($wake_time);
echo "Awake at: " . date('H:i:s');
?>

Output:

Start: 14:30:00
After 2 seconds: 14:30:02
After 0.5 more seconds: 14:30:02

Sleeping until: 14:30:03
Awake at: 14:30:03

Use Cases:

  • Rate limiting API requests
  • Simulating long-running processes
  • Scheduled task execution
  • Preventing server overload

🔹 Connection Handling

Monitor and control client connections to your PHP scripts. These functions help handle situations where users close their browser or connection drops.

<?php
// Check connection status
$status = connection_status();
switch ($status) {
    case CONNECTION_NORMAL:
        echo "Connection: Normal\n";
        break;
    case CONNECTION_ABORTED:
        echo "Connection: Aborted by user\n";
        break;
    case CONNECTION_TIMEOUT:
        echo "Connection: Timeout\n";
        break;
}

// Check if connection was aborted
if (connection_aborted()) {
    echo "User disconnected!\n";
} else {
    echo "User still connected\n";
}

// Continue script even if user disconnects
ignore_user_abort(true);
echo "Script will continue even if user closes browser";
?>

Output:

Connection: Normal
User still connected
Script will continue even if user closes browser

🔹 Defining Constants

Create constants that cannot be changed during script execution. Use define() for simple constants or const for class constants and better performance.

<?php
// Define constants
define("SITE_NAME", "My Website");
define("MAX_USERS", 100);
define("DEBUG_MODE", true);

echo "Site: " . SITE_NAME . "\n";
echo "Max users: " . MAX_USERS . "\n";
echo "Debug: " . (DEBUG_MODE ? "On" : "Off") . "\n\n";

// Check if constant exists
if (defined("SITE_NAME")) {
    echo "SITE_NAME is defined\n";
}

// Case-insensitive constant (deprecated in PHP 7.3+)
define("VERSION", "1.0.0");
echo "Version: " . VERSION . "\n\n";

// Get all defined constants
$constants = get_defined_constants(true);
echo "User constants: " . count($constants['user']);
?>

Output:

Site: My Website
Max users: 100
Debug: On

SITE_NAME is defined
Version: 1.0.0

User constants: 4

🔹 Script Execution Control

Control how long scripts can run and how much memory they can use. These functions help prevent scripts from consuming too many server resources.

<?php
// Get current time limit
echo "Current time limit: " . ini_get('max_execution_time') . " seconds\n";

// Set time limit to 60 seconds
set_time_limit(60);
echo "New time limit: 60 seconds\n\n";

// Get memory limit
echo "Memory limit: " . ini_get('memory_limit') . "\n";

// Get current memory usage
echo "Memory used: " . round(memory_get_usage() / 1024 / 1024, 2) . " MB\n";
echo "Peak memory: " . round(memory_get_peak_usage() / 1024 / 1024, 2) . " MB\n\n";

// Disable time limit (use carefully!)
set_time_limit(0);
echo "Time limit disabled (infinite execution)";
?>

Output:

Current time limit: 30 seconds
New time limit: 60 seconds

Memory limit: 128M
Memory used: 2.5 MB
Peak memory: 2.8 MB

Time limit disabled (infinite execution)

🔹 Packing and Unpacking Data

Convert data between binary and other formats using pack() and unpack(). This is useful for reading binary files, network protocols, and low-level data manipulation.

<?php
// Pack integers into binary string
$packed = pack("C3", 65, 66, 67);
echo "Packed: " . bin2hex($packed) . "\n";

// Unpack binary data
$unpacked = unpack("C3", $packed);
echo "Unpacked: ";
print_r($unpacked);
echo "\n";

// Pack string
$text = pack("A10", "Hello");
echo "Packed text: '$text'\n";
echo "Length: " . strlen($text) . "\n\n";

// Convert between formats
$number = 1234;
$hex = dechex($number);
$binary = decbin($number);
echo "Decimal: $number\n";
echo "Hex: $hex\n";
echo "Binary: $binary";
?>

Output:

Packed: 414243
Unpacked: Array ( [1] => 65 [2] => 66 [3] => 67 )

Packed text: 'Hello '
Length: 10

Decimal: 1234
Hex: 4d2
Binary: 10011010010

🔹 Useful Utility Functions

Miscellaneous helper functions for common tasks like highlighting PHP code, evaluating strings as code, and getting function information.

<?php
// Highlight PHP syntax
$code = '<?php echo "Hello World"; ?>';
echo "Highlighted code:\n";
echo highlight_string($code, true) . "\n\n";

// Get list of defined functions
$functions = get_defined_functions();
echo "Built-in functions: " . count($functions['internal']) . "\n";
echo "User functions: " . count($functions['user']) . "\n\n";

// Check if function exists
if (function_exists('strlen')) {
    echo "strlen() exists\n";
}

// Get function arguments
function greet($name, $age = 18) {
    return "Hello $name, age $age";
}

$reflection = new ReflectionFunction('greet');
echo "greet() has " . $reflection->getNumberOfParameters() . " parameters";
?>

Output:

Highlighted code:
<?php echo "Hello World" ; ?>

Built-in functions: 1247
User functions: 1

strlen() exists
greet() has 2 parameters

🔹 Practical Examples

Real-world applications combining miscellaneous functions for common programming tasks like generating tokens, rate limiting, and system monitoring.

<?php
// Generate secure token
function generateToken($length = 32) {
    return bin2hex(random_bytes($length / 2));
}
echo "Secure token: " . generateToken(16) . "\n\n";

// Simple rate limiter
function rateLimiter($key, $max_requests = 5, $period = 60) {
    static $requests = [];
    $now = time();
    
    if (!isset($requests[$key])) {
        $requests[$key] = [];
    }
    
    // Remove old requests
    $requests[$key] = array_filter($requests[$key], function($time) use ($now, $period) {
        return ($now - $time) < $period;
    });
    
    if (count($requests[$key]) >= $max_requests) {
        return false;
    }
    
    $requests[$key][] = $now;
    return true;
}

echo "Request 1: " . (rateLimiter('user123') ? "Allowed" : "Blocked") . "\n";
echo "Request 2: " . (rateLimiter('user123') ? "Allowed" : "Blocked");
?>

Output:

Secure token: a3f7b9c2e1d4f6a8

Request 1: Allowed
Request 2: Allowed

🧠 Test Your Knowledge

Which function generates a unique identifier?