April 29, 2025 - 17:52
Reusable PHP Functions for Various Projects Image
PHP

Reusable PHP Functions for Various Projects

Comments

In PHP projects, frequently needed utility functions can be grouped under categories such as database operations, security, data formatting, performance, and file handling. These functions help speed up development and prevent code repetition.


1. Security Functions

1.1. Protection Against SQL Injection (Data Sanitization)

PHP
function sanitizeInput($data, $db) {
    return htmlspecialchars(strip_tags($db->quote($data)));
}
Usage:
PHP
$username = sanitizeInput($_POST['username'], $pdo);

This function helps prevent SQL Injection attacks.


1.2. Strong Password Hashing

PHP
function hashPassword($password) {
    return password_hash($password, PASSWORD_BCRYPT);
}
Usage:
PHP
$hashedPassword = hashPassword('StrongPassword123');
Verification:
PHP
if (password_verify($password, $hashedPassword)) {
    echo 'Password is correct!';
}

This function uses bcrypt to securely store passwords.


1.3. Secure Random Token Generation

PHP
function generateToken($length = 32) {
    return bin2hex(random_bytes($length));
}
Usage:
PHP
$csrfToken = generateToken();

This function generates a secure random string for CSRF tokens or API keys.


2. Database Functions

2.1. Retrieve All Users

PHP
function getAllUsers($db) {
    $stmt = $db->query('SELECT * FROM users');
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
Usage:
PHP
$users = getAllUsers($pdo);
print_r($users);

This function retrieves all users from the database.


2.2. Get User Info by ID

PHP
function getUserById($db, $id) {
    $stmt = $db->prepare('SELECT * FROM users WHERE id = :id');
    $stmt->bindParam(':id', $id, PDO::PARAM_INT);
    $stmt->execute();
    return $stmt->fetch(PDO::FETCH_ASSOC);
}
Usage:
PHP
$user = getUserById($pdo, 1);
print_r($user);

This function retrieves user information by given ID.


3. Data Formatting Functions

3.1. Format Dates

PHP
function formatDate($date, $format = 'd-m-Y H:i') {
    return date($format, strtotime($date));
}
Usage:
PHP
echo formatDate('2024-03-05 15:30:00');

This function makes date formats more readable.


3.2. Truncate Text

PHP
function truncateText($text, $length = 100) {
    return strlen($text) > $length ? substr($text, 0, $length) . '...' : $text;
}
Usage:
PHP
echo truncateText('This is a very long text that needs to be shortened.', 20);

This function shortens long text to a defined length.


4. File and Directory Functions

4.1. Human-Readable File Size

PHP
function formatFileSize($bytes) {
    $sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
    $factor = floor((strlen($bytes) - 1) / 3);
    return sprintf('%.2f %s', $bytes / pow(1024, $factor), $sizes[$factor]);
}
Usage:
PHP
echo formatFileSize(2048000); // 1.95 MB

This function converts file size to a human-readable format.


4.2. List Files in a Directory

PHP
function listFiles($dir) {
    return array_diff(scandir($dir), ['.', '..']);
}
Usage:
PHP
print_r(listFiles('uploads'));

This function lists all files in the given directory.


5. Performance Optimization

5.1. Measure Page Load Time

PHP
function startTimer() {
    global $start_time;
    $start_time = microtime(true);
}
function endTimer() {
    global $start_time;
    return round(microtime(true) - $start_time, 5) . ' seconds';
}
Usage:
PHP
startTimer();
// Your process here
echo 'Page load time: ' . endTimer();

This function measures the execution time of PHP scripts.


5.2. Measure Memory Usage

PHP
function getMemoryUsage() {
    return round(memory_get_usage() / 1024 / 1024, 2) . ' MB';
}
Usage:
PHP
echo getMemoryUsage();

This function measures the memory used by the PHP script.


6. Miscellaneous Utility Functions

6.1. Get Client IP Address

PHP
function getClientIP() {
    return $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
}
Usage:
PHP
echo getClientIP();

This function returns the IP address of the client.


6.2. Generate Random Password

PHP
function generatePassword($length = 12) {
    return substr(str_shuffle('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*'), 0, $length);
}
Usage:
PHP
echo generatePassword(16);

This function generates a strong random password.

Related Articles

Comments ()

No comments yet. Be the first to comment!

Leave a Comment