整理 13 個 PHP 專案中高頻使用的實用函式,涵蓋字串處理、檔案操作、安全防護、時間格式化等,可直接複製套用。
function encryptDecrypt($key, $string, $decrypt) {
if ($decrypt) {
return rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($string), MCRYPT_MODE_CBC, md5(md5($key))), "\0");
} else {
return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $string, MCRYPT_MODE_CBC, md5(md5($key))));
}
}
// 使用:encryptDecrypt('pwd', '文字', 0) 加密;encryptDecrypt('pwd', '密文', 1) 解密
注意:MCrypt 已棄用,新專案建議改用 OpenSSL 或 Sodium。
function generateRandomString($length = 10) {
$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$str = '';
for ($i = 0; $i < $length; $i++) {
$str .= $chars[random_int(0, strlen($chars) - 1)];
}
return $str;
}
function getExtension($filename) {
return strtolower(pathinfo($filename, PATHINFO_EXTENSION));
}
function formatSize($bytes) {
$units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
$i = $bytes > 0 ? floor(log($bytes, 1024)) : 0;
return round($bytes / pow(1024, $i), 2) . ' ' . $units[$i];
}
function stringParser($string, array $replacer) {
return str_replace(array_keys($replacer), array_values($replacer), $string);
}
function listDirFiles($dirPath) {
if ($handle = opendir($dirPath)) {
while (false !== ($file = readdir($handle))) {
if (!is_dir($dirPath . $file)) echo "filename: $file
";
}
closedir($handle);
}
}
function curPageURL() {
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$port = ($_SERVER['SERVER_PORT'] != '80') ? ':' . $_SERVER['SERVER_PORT'] : '';
return $protocol . '://' . $_SERVER['SERVER_NAME'] . $port . $_SERVER['REQUEST_URI'];
}
function download($filename) {
if (isset($filename) && file_exists($filename)) {
header('Content-Length: ' . filesize($filename));
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($filename) . '"');
readfile($filename);
exit;
}
echo "檔案不存在!";
}
function cutStr($string, $sublen, $start = 0, $code = 'UTF-8') {
if ($code === 'UTF-8') {
preg_match_all('/./u', $string, $matches);
$slice = array_slice($matches[0], $start, $sublen);
return implode('', $slice) . (count($matches[0]) > $start + $sublen ? '...' : '');
}
// GB2312 等雙位元組編碼處理略...
}
function getRealIp() {
$keys = ['HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'REMOTE_ADDR'];
foreach ($keys as $key) {
if (!empty($_SERVER[$key]) && strcasecmp($_SERVER[$key], 'unknown')) {
return $_SERVER[$key];
}
}
return 'unknown';
}
function injCheck($sql) {
$pattern = '/select|insert|update|delete|union|into|load_file|outfile/i';
if (preg_match($pattern, $sql)) { exit('非法字元!'); }
return $sql;
}
function message($title, $msg, $jumpUrl) {
$html = '<!DOCTYPE html><html><head><meta charset="utf-8"><title>' . $title . '</title>';
$html .= '<style>body{font:14px/1.5 sans-serif;text-align:center;padding-top:100px}.btn{display:inline-block;margin-top:20px;padding:10px 20px;background:#2c91c6;color:#fff;text-decoration:none;border-radius:4px}</style>';
$html .= '</head><body><h3>' . $title . '</h3><p>' . $msg . '</p>';
$html .= '<a class="btn" href="' . $jumpUrl . '">立即跳轉</a>';
$html .= '<script>setTimeout(()=>location.href="' . $jumpUrl . '", 3000)</script></body></html>';
exit($html);
}
function changeTimeType($seconds) {
if ($seconds >= 3600) {
$h = floor($seconds / 3600);
$m = gmstrftime('%M:%S', $seconds % 3600);
return "$h:$m";
}
return gmstrftime('%H:%M:%S', $seconds);
}