萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 常用工具函式庫 13 選:加密、隨機字串、檔案操作、IP 取得、SQL 防注入等

整理 13 個 PHP 專案中高頻使用的實用函式,涵蓋字串處理、檔案操作、安全防護、時間格式化等,可直接複製套用。

1. 可逆加密解密(Base64 + MCrypt)

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。

2. 產生隨機字串

function generateRandomString($length = 10) {
    $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $str = '';
    for ($i = 0; $i < $length; $i++) {
        $str .= $chars[random_int(0, strlen($chars) - 1)];
    }
    return $str;
}

3. 取得副檔名

function getExtension($filename) {
    return strtolower(pathinfo($filename, PATHINFO_EXTENSION));
}

4. 檔案大小人性化格式化

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];
}

5. 標籤字串替換(簡易模板引擎)

function stringParser($string, array $replacer) {
    return str_replace(array_keys($replacer), array_values($replacer), $string);
}

6. 列出目錄檔案

function listDirFiles($dirPath) {
    if ($handle = opendir($dirPath)) {
        while (false !== ($file = readdir($handle))) {
            if (!is_dir($dirPath . $file)) echo "filename: $file
"; } closedir($handle); } }

7. 取得當前完整 URL

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'];
}

8. 強制下載檔案

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 "檔案不存在!";
}

9. 多位元組安全截斷字串(支援 UTF-8/GB2312)

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 等雙位元組編碼處理略...
}

10. 取得客戶端真實 IP(支援代理)

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';
}

11. 簡易 SQL 注入過濾(示範用,實務請用 Prepared Statements)

function injCheck($sql) {
    $pattern = '/select|insert|update|delete|union|into|load_file|outfile/i';
    if (preg_match($pattern, $sql)) { exit('非法字元!'); }
    return $sql;
}

12. 頁面提示與自動跳轉

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);
}

13. 秒數轉時分秒格式

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);
}
copyright © 萬盛學電腦網 all rights reserved