You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

47 lines
2.3 KiB

<?php
class Helper {
public static function generateId() { return uniqid('', true); }
public static function formatDateTime($timestamp, $format = 'Y-m-d H:i:s') {
if (is_numeric($timestamp)) { return date($format, $timestamp); }
if (is_string($timestamp)) { return date($format, strtotime($timestamp)); }
return date($format);
}
public static function validateEmail($email) { return filter_var($email, FILTER_VALIDATE_EMAIL) !== false; }
public static function validateIp($ip) { return filter_var($ip, FILTER_VALIDATE_IP) !== false; }
public static function getClientIp() {
$ip = $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1';
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$forwardedIps = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
$ip = trim($forwardedIps[0]);
} elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
}
return $ip;
}
public static function encryptPassword($password) { return password_hash($password, PASSWORD_DEFAULT); }
public static function verifyPassword($password, $hash) { return password_verify($password, $hash); }
public static function truncate($string, $length = 100, $suffix = '...') {
if (strlen($string) <= $length) { return $string; }
return substr($string, 0, $length - strlen($suffix)) . $suffix;
}
public static function generateRandomString($length = 16, $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') {
$randomString = '';
$charactersLength = strlen($characters);
for ($i = 0; $i < $length; $i++) { $randomString .= $characters[rand(0, $charactersLength - 1)]; }
return $randomString;
}
public static function formatFileSize($bytes, $precision = 2) {
$units = ['B', 'KB', 'MB', 'GB', 'TB'];
$bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
$pow = min($pow, count($units) - 1);
$bytes /= pow(1024, $pow);
return round($bytes, $precision) . ' ' . $units[$pow];
}
public static function isPortAvailable($host, $port, $timeout = 1) {
$socket = @fsockopen($host, $port, $errno, $errstr, $timeout);
if ($socket) { fclose($socket); return false; }
return true;
}
}