
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)
function sanitizeInput($data, $db) {
return htmlspecialchars(strip_tags($db->quote($data)));
}
$username = sanitizeInput($_POST['username'], $pdo);
This function helps prevent SQL Injection attacks.
1.2. Strong Password Hashing
function hashPassword($password) {
return password_hash($password, PASSWORD_BCRYPT);
}
$hashedPassword = hashPassword('StrongPassword123');
if (password_verify($password, $hashedPassword)) {
echo 'Password is correct!';
}
This function uses bcrypt to securely store passwords.
1.3. Secure Random Token Generation
function generateToken($length = 32) {
return bin2hex(random_bytes($length));
}
$csrfToken = generateToken();
This function generates a secure random string for CSRF tokens or API keys.
2. Database Functions
2.1. Retrieve All Users
function getAllUsers($db) {
$stmt = $db->query('SELECT * FROM users');
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
$users = getAllUsers($pdo);
print_r($users);
This function retrieves all users from the database.
2.2. Get User Info by ID
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);
}
$user = getUserById($pdo, 1);
print_r($user);
This function retrieves user information by given ID.
3. Data Formatting Functions
3.1. Format Dates
function formatDate($date, $format = 'd-m-Y H:i') {
return date($format, strtotime($date));
}
echo formatDate('2024-03-05 15:30:00');
This function makes date formats more readable.
3.2. Truncate Text
function truncateText($text, $length = 100) {
return strlen($text) > $length ? substr($text, 0, $length) . '...' : $text;
}
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
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]);
}
echo formatFileSize(2048000); // 1.95 MB
This function converts file size to a human-readable format.
4.2. List Files in a Directory
function listFiles($dir) {
return array_diff(scandir($dir), ['.', '..']);
}
print_r(listFiles('uploads'));
This function lists all files in the given directory.
5. Performance Optimization
5.1. Measure Page Load Time
function startTimer() {
global $start_time;
$start_time = microtime(true);
}
function endTimer() {
global $start_time;
return round(microtime(true) - $start_time, 5) . ' seconds';
}
startTimer();
// Your process here
echo 'Page load time: ' . endTimer();
This function measures the execution time of PHP scripts.
5.2. Measure Memory Usage
function getMemoryUsage() {
return round(memory_get_usage() / 1024 / 1024, 2) . ' MB';
}
echo getMemoryUsage();
This function measures the memory used by the PHP script.
6. Miscellaneous Utility Functions
6.1. Get Client IP Address
function getClientIP() {
return $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
}
echo getClientIP();
This function returns the IP address of the client.
6.2. Generate Random Password
function generatePassword($length = 12) {
return substr(str_shuffle('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*'), 0, $length);
}
echo generatePassword(16);
This function generates a strong random password.
Related Articles
